【问题标题】:plot a stacked bar chart matplotlib pandas绘制堆积条形图 matplotlib pandas
【发布时间】:2018-11-26 17:51:18
【问题描述】:

我想绘制此数据框,但出现错误。 这是我的 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-axis 中,y-axisQuestion text 中的final-formula 被堆叠。

所以在这里我有三种Question text,应该有三个堆叠条。和我一样4 month,总共有 4 个酒吧。

类似this 的东西,但我应用了这个但没有用。 我错过了什么吗?

这张图片没有堆叠。就像所有question text 都已经总结出来了。我希望每个Question Text 都有堆叠。

【问题讨论】:

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


    【解决方案1】:

    你错过了groupby之后的聚合步骤,即sum()

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

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

    【讨论】:

    • 嗯,你是对的,以前我有聚合功能,但还有其他错误。为响应和您的时间欢呼。有效。还有一个问题,有没有什么方法可以在不使用 group by 和聚合的情况下启动这个堆栈栏?
    • 另外,我的数据框中还有另一个数字列,我从 df 中删除了它以成功运行您的代码(因为它将该数字添加到最终公式中,因此在 y 轴上显示的结果不正确)。如何在保留该列的同时该代码正确运行?
    • 您可以在构建df 时删除该列,在drop(column_name, 1) 之前使用groupby
    • 有什么阻止您使用groupby?在我看来,这种方式非常自然和直观。
    • 事实上,groupby 是一个合并数据的关键函数,我暂时想不出任何其他方法。
    猜你喜欢
    • 2016-05-24
    • 2018-03-10
    • 2019-09-27
    • 1970-01-01
    • 2012-09-17
    • 2021-12-27
    相关资源
    最近更新 更多