带有 pandas 的多个堆叠条形图 [英] Multiple stacked bar plot with pandas

查看:66
本文介绍了带有 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)

会产生以下情节:

如您所见,每个群集中的条形图相互重叠,这不是我想要实现的.我希望将同一群集中的条形图彼此相邻地绘制.我尝试使用位置"参数,但收效甚微.

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?

推荐答案

您可以通过移动bar-plotposition参数,使它们彼此相邻,如下所示:

You could do it by shifting the position parameter of a bar-plot so that they are adjacent to each other as shown:

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

这篇关于带有 pandas 的多个堆叠条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆