Matplotlib - 来自已创建绘图的子图

Matplotlib - Subplot from already created plots

我有一个函数 returns 特定列的绘图

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")

我想制作 4 个这样的图,并将它们呈现为 2 行 2 列的子图。但是如果我尝试

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

我明白了

这显然不是我所期望的

提前感谢您的帮助!

您需要绘制 一个已经存在的坐标轴。所以你的函数应该将轴作为输入:

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)

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

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

在这一行 plt.subplot(1,2,1) 中,您要指定此排列中的两个图:一行和两列,并将图放在左侧。

(1,2,1) 指定(行数、列数、要绘制的索引)。

由于您希望子图按 2 对 2 排列,请指定 (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 的详细信息进行处理。您还可以 share axes 并使用其他几个参数和参数: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.subplot.html

一个最小的工作示例将更好地识别问题并获得更好的答案。