简体   繁体   English

带有熊猫的多个堆叠条形图

[英]Multiple stacked bar plot with pandas

I am trying to make a multiple stacked bar plot with pandas but I'm running into issues.我试图用熊猫制作一个多堆叠条形图,但我遇到了问题。 Here is a sample code:这是一个示例代码:

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)

Which produces the following plot:产生以下情节:

在此处输入图片说明

As you can see, the bars within each cluster are plotted on top of each other, which is not what I want to achieve.如您所见,每个集群内的条形图都绘制在彼此的顶部,这不是我想要实现的。 I want the bars within the same cluster to be plotted next to each other.我希望同一个集群中的条形图彼此相邻绘制。 I tried to play with the "position" argument but without much success.我试图玩弄“位置”的论点,但没有取得太大的成功。

Any idea on how to achieve this?关于如何实现这一目标的任何想法?

You could do it by shifting the position parameter of a bar-plot so that they are adjacent to each other as shown:您可以通过移动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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM