【问题标题】:Matplotlib - Subplot from already created plotsMatplotlib - 来自已创建图的子图
【发布时间】:2020-05-05 16:50:27
【问题描述】:

我有一个函数可以返回特定列的图

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

我明白了

这显然不是我所期望的

提前感谢您的帮助!

【问题讨论】:

  • 对于出现的错误,代码仍然有点过于复杂。也许让它更短并符合minimal reproducible example
  • 代码其实没那么复杂。这就是该函数创建并返回一个条形图的全部内容,例如示例图像中显示的条形图。现在的事情是使用这个函数来创建子图。而不是plt.subplot(1,2,1) \n plt.bar(x,y) 使用这个:plt.subplot(1,2,1) \n class_distribution(colname)
  • 如果你想要四个地块,你应该使用plt.subplot(2, 2, ...)。然后通过plt.subplot(2, 2, i) 其中i = (1, 2, 3, 4) 选择其中一个子图后,您需要绘制您想要绘制的任何内容。
  • 它不起作用。我得到与plt.subplot(1,2,i) 的代码完全相同的输出

标签: python pandas matplotlib subplot


【解决方案1】:

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

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) 指定(行数、列数、要绘制的索引)。

    由于您希望以 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

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

    【讨论】:

      猜你喜欢
      • 2017-08-26
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多