gpt4 book ai didi

python - 带有 pandas 的多个堆叠条形图

转载 作者:行者123 更新时间:2023-12-03 03:03:34 24 4
gpt4 key购买 nike

我正在尝试用 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)

生成以下图:

enter image description here

正如您所看到的,每个簇内的条形图都绘制在彼此之上,这不是我想要实现的目标。我希望同一簇内的条形图彼此相邻绘制。我尝试使用“位置”论证,但没有取得多大成功。

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

最佳答案

您可以通过移动条形图position参数来实现这一点,使它们彼此相邻,如下所示:

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()

enter image description here

关于python - 带有 pandas 的多个堆叠条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39013425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com