将图形插入其中一个子图中

时间:2018-11-05 16:45:19

标签: python matplotlib seaborn subplot

我在matplotlib中有一个子图网格。
对于其中大多数,我定义了子图将正常显示的情况。 对于其中一个,我封装了一个函数distribution_of_graphs中的逻辑。

我可以使用该函数返回的图形作为子图之一吗?

def distribution_of_graphs(net):

    # Some logic to get df from net object
    df = net.logic()

    pal = sns.cubehelix_palette(len(list(df)), rot=-.25, light=.7)
    g = sns.FacetGrid(df, row="grad", hue="grad", aspect=15, height=5, palette=pal)

    # Draw the densities in a few steps
    g.map(sns.kdeplot, "x", clip_on=False, shade=True, alpha=0.6, lw=1.5, bw=.2)
    g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw=.2) ## White contour
    g.map(plt.axhline, y=0, lw=2, clip_on=False) ## Will serve as the x axis

    # Define and use a simple function to label the plot in axes coordinates
    def label(x, color, label):
        ax = plt.gca()
        ax.text(0, .2, label, fontweight="bold", color=color,
                ha="left", va="bottom", transform=ax.transAxes)
        ax.set_xlim([-1.5, 1.5])
    g.map(label, "x")

    # Set the subplots to overlap
    g.fig.subplots_adjust(hspace=-.75)

    # Remove axes details that don't play well with overlap
    g.set_titles("")
    g.set(yticks=[])
    g.despine(bottom=True, left=True)
    return g

此函数创建以下图像: enter image description here

我想使用该函数的结果图作为下图的ax4:

plt.figure(figsize=(15,15))
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=1)
ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=1)
ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0), colspan=2)
sns.lineplot(xaxis, net.weight_stats['gradWinp'], ax=ax1, color='blue').set_title('grad W1')
sns.lineplot(xaxis, net.weight_stats['gradWout'], ax=ax2, color='red').set_title('grad W2')
sns.lineplot(xaxis, net.weight_stats['gradWinp'], ax=ax3, color='blue', label='grad W1')
sns.lineplot(xaxis, net.weight_stats['gradWout'], ax=ax3, color='red', label='grad W2')

# What I am missing
ax4.plot(distribution_of_graphs(net))

# Previos behavior working properly
#sns.kdeplot(norm_dW1, shade=True, ax=ax4)
#sns.kdeplot(norm_dW2, shade=True, ax=ax4)

plt.plot()

现在该空间留为空白,并通过函数在单独的图中创建了绘图:

enter image description here 出现错误消息:TypeError: float() argument must be a string or a number, not 'FacetGrid'

谢谢!

1 个答案:

答案 0 :(得分:0)

两个建议:

1)您可以在函数内部绘图。举一个简单的例子

def plotxy(x,y):
    plot(x,y)
    return

subplot(4,1,3)
plotxy(x,y) # will plot in the 4th subplot

2)将轴手柄传递到您的函数中

def plotxy(ax,x,y):
    ax.plot(x,y)
    return

plotxy(ax4,x,y)
相关问题