【发布时间】: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