【问题标题】:Multiple stacked bar plot with pandas带有熊猫的多个堆积条形图
【发布时间】:2016-08-18 17:16:18
【问题描述】:

我正在尝试使用 pandas 制作多个堆叠的条形图,但遇到了问题。这是一个示例代码:

import pandas as pd

df = pd.DataFrame({'a':[10, 20], 'b': [15, 25], 'c': [35, 40], 'd':[45, 50]}, index=['john', 'bob'])

ax = df[['a', 'c']].plot.bar(width=0.1, stacked=True)
ax=df[['b', 'd']].plot.bar(width=0.1, stacked=True, ax=ax)
df[['a', 'd']].plot.bar(width=0.1, stacked=True, ax=ax)

这会产生以下情节:

如您所见,每个集群中的条都被绘制在彼此之上,这不是我想要实现的。我希望将同一集群中的条形图彼此相邻绘制。我尝试使用“位置”参数,但没有取得多大成功。

知道如何实现这一目标吗?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您可以通过移动bar-plotposition 参数来做到这一点,使它们彼此相邻,如图所示:

    matplotlib.style.use('ggplot')
    
    fig, ax = plt.subplots()
    df[['a', 'c']].plot.bar(stacked=True, width=0.1, position=1.5, colormap="bwr", ax=ax, alpha=0.7)
    df[['b', 'd']].plot.bar(stacked=True, width=0.1, position=-0.5, colormap="RdGy", ax=ax, alpha=0.7)
    df[['a', 'd']].plot.bar(stacked=True, width=0.1, position=0.5, colormap="BrBG", ax=ax, alpha=0.7)
    plt.legend(loc="upper center")
    plt.show()
    

    【讨论】:

    • 我很困惑。文档说“位置”参数从 0 到 1,但您使用的值低于 0 和高于 1。这是如何工作的?
    • 很好的观察!如您所知,pandas 继承了 matplotlib 对象中存在的关键字参数,您可以利用它来调整各种设置。一种这样的情况是使用matplotlib - bar 绘图的align 参数来更改pandas - bar 绘图的position 参数。您也可以参考 source code,它使用 align 选项,它允许设置两个 pos/neg 浮点数。
    • 好的,所以如果我理解正确,它可以工作,因为在引擎盖下,熊猫栏只是一个常规的 matplotlib 栏,其“对齐”属性的值确实低于 0 和高于 1。感谢解释!
    • 如何减少两个组之间的空间?