Matplotlib - 利用已创建的图形创建子图。

3
我有一个函数,它返回特定列的绘图。
def class_distribution(colname):
    df = tweets_best.groupby(["HandLabel", colname]).size().to_frame("size")
    df['percentage'] = df.groupby(level=0).transform(lambda x: (x / x.sum()).round(2))
    df_toPlot = df[["percentage"]]

    plot = df_toPlot.unstack().plot.bar()
    plt.legend(df_toPlot.index.get_level_values(level = 1))
    plt.title("{} predicted sentiment distribution".format(colname))
    plt.ylim((0,1))
    plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
    return plot.get_figure()

一个示例输出看起来像这样

nb = class_distribution("Naive_Bayes")

example_output

我希望能够生成4个类似这样的图表,并将它们作为子图以2行2列的形式呈现。但是,如果我尝试这样做,...
plt.figure()
plt.subplot(1,2,1)
nb
plt.subplot(1,2,2)
sn

我得到

example_output2

我肯定不会期望这种情况发生

提前感谢您的帮助!


1
代码对于所呈现的错误来说还是有点太复杂了。也许可以将其缩短并与一个[示例]保持一致。 - Trilarion
代码并不是非常复杂。它主要是关于函数创建和返回一个条形图,就像示例图片中呈现的那样。现在的问题是如何使用此函数创建子图。不要使用plt.subplot(1,2,1) \n plt.bar(x,y)而是使用:plt.subplot(1,2,1) \n class_distribution(colname) - GKroch
如果您想要四个图表,您应该使用 plt.subplot(2, 2, ...)。然后通过 plt.subplot(2, 2, i) 选择其中一个子图,其中 i = (1, 2, 3, 4),然后绘制您想要绘制的内容。 - a_guest
它不起作用。我得到的输出与使用 plt.subplot(1,2,i) 代码的情况完全相同。 - GKroch
2个回答

2

您需要将图表绘制在已经存在的坐标轴上。因此,您的函数应该以坐标轴作为输入:

def class_distribution(colname, ax=None):
    ax = ax or plt.gca()

    df = ...  # create dataframe based on function input

    df.unstack().plot.bar(ax=ax)
    ax.legend(...)
    ax.set_title("{} predicted sentiment distribution".format(colname))
    ax.set_ylim((0,1))
    ax.yaxis.set_major_formatter(PercentFormatter(1))
    return ax

接下来,您可以创建一个图形和一个或多个子图来绘制:

fig = plt.figure()

ax1 = fig.add_subplot(1,2,1)
class_distribution("colname1", ax=ax1)

ax2 = fig.add_subplot(1,2,2)
class_distribution("colname2", ax=ax2)

2

实际上,根据您的代码,您的输出正是您所期望的:

plt.figure()
plt.subplot(1,2,1)
nb
plt.subplot(1,2,2)
sn

在这行代码中 plt.subplot(1,2,1),您正在指定这种排列方式的两个图:一行和两列,并将图形放置在左侧。 (1,2,1) 指定了(行数、列数、要绘制的索引)。
由于您想要子图以 2x2 的方式排列,因此请指定 (2,2,i),其中 i 是索引。这将排列您的图形:
plt.figure()
plt.subplot(2,2,1)
{plot in upper left}
plt.subplot(2,2,2)
{plot in upper right}
plt.subplot(2,2,3)
{plot in lower left}
plt.subplot(2,2,4)
{plot in lower right}

此外,您可以将轴处理为“ ImportanceOfBeingEarnest”细节。 您还可以共享轴并利用其他几个参数和参数: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.subplot.html 最小工作示例将更好地确定问题并获得更好的答案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接