用堆积的DataFlot绘制堆叠的直方图
问题描述:
我想要堆叠的直方图,其中不同的类是可见的。用堆积的DataFlot绘制堆叠的直方图
目前我有没有与此代码类的直方图:
plt.hist(hist_matrix2.column_name)
产生该直方图:
并用相同的数据的另一直方图,由分组此代码的类别:
hist_matrix2.groupby("number").column_name.plot.hist(alpha=0.5, bins = [0,5,10,15,20,25,30], stacked = True)
产生这个柱状图:
正如你所看到的类是有,但它不是堆放,虽然参数设置。我能做些什么来堆栈类?
答
plt.hist有一个内置的叠加标志,您可以设置:响应
plt.hist(hist_matrix2.column_name, stacked=True)
编辑你的问题,长期的数据(多层次堆叠)首先你需要重组的数据为列表清单:
wide=hist_matrix2.pivot(columns='number', values='column_name')
#This creates many missing values which pandas does not like, so we drop them
widelist=[wide[col].dropna() for col in wide.columns]
# and the stacked graph is here
plt.hist(widelist,stacked=True)
plt.show()
但是,这不是由类分开。如果你的类是按列分隔的,这个堆栈就可以工作。在我的例子中,'数字'是类标签。随着groupby我得到分离类,但他们叠加,我想他们堆积(plot2)。 –