绘制堆积条形图matplotlib熊猫

时间:2018-06-17 20:05:04

标签: pandas matplotlib bar-chart data-visualization data-analysis

我想绘制这个数据框,但是我收到了一个错误。 这是我的df:

            6month  final-formula   Question Text
166047.0       1       0.007421         bathing
166049.0       1       0.006441        dressing
166214.0       1       0.001960         feeding
166216.0       2       0.011621         bathing
166218.0       2       0.003500        dressing
166220.0       2       0.019672         feeding
166224.0       3       0.012882         bathing
166226.0       3       0.013162        dressing
166229.0       3       0.008821         feeding
160243.0       4       0.023424         bathing
156876.0       4       0.000000        dressing
172110.0       4       0.032024         feeding

如何根据Question text绘制堆积条? 我尝试了一些代码,但引发了错误。

dffinal.groupby(['6month','Question Text']).unstack('Question Text').plot(kind='bar',stacked=True,x='6month', y='final-formula')
import matplotlib.pyplot as plt
plt.show()

实际上,我希望6month列位于x-axisfinal-formulay-axisQuestion text正在堆叠。

所以在这里我有三种Question text,三个堆叠的酒吧应该在那里。因为我有4 month,总共有4个吧。

this这样的东西,但是我应用了这个并且没有用。 我错过了什么吗?

这张照片没有堆叠它们。就像所有question text一样,总结了它。我希望每个Question Text都有堆叠。

enter image description here

1 个答案:

答案 0 :(得分:1)

您错过了groupby之后的汇总步骤,即sum()

df = dffinal.groupby(['6month','Question Text']).sum().unstack('Question Text')
df.columns = df.columns.droplevel()
df.plot(kind='bar', stacked=True)

为了保持图例的一致性,我从列中删除了多索引级别。