【问题标题】:Plug in a figure into one of the subplots将图形插入其中一个子图中
【发布时间】:2018-11-05 16:45:19
【问题描述】:

我在 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

此函数创建以下图像:

我想使用该函数的结果图作为下图的 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()

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

带有错误消息:TypeError: float() argument must be a string or a number, not 'FacetGrid'

谢谢!

【问题讨论】:

  • 在这种情况下,您宁愿不使用 FacetGrid,而是使用 ax4 在您的图中创建 4 个不同的轴并将 kdeplots 绘制到它们。如果您需要这方面的帮助,我建议您在问题中提供minimal reproducible example(即可运行代码)。

标签: python matplotlib seaborn subplot


【解决方案1】:

两个建议:

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)

【讨论】:

    猜你喜欢
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    相关资源
    最近更新 更多