[英]Multiple stacked bar plot with 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)
产生以下情节:
如您所见,每个集群内的条形图都绘制在彼此的顶部,这不是我想要实现的。 我希望同一个集群中的条形图彼此相邻绘制。 我试图玩弄“位置”的论点,但没有取得太大的成功。
关于如何实现这一目标的任何想法?
您可以通过移动bar-plot
的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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.