Matplotlib中的水平堆积条形图 [英] Horizontal stacked bar chart in Matplotlib

查看:329
本文介绍了Matplotlib中的水平堆积条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用matplotlib创建水平堆叠的条形图,但是我看不到如何使条形实际堆叠而不是全部从y轴开始.

I'm trying to create a horizontal stacked bar chart using matplotlib but I can't see how to make the bars actually stack rather than all start on the y-axis.

这是我的测试代码.

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plot_chart(df, fig, ax)
ind = arange(df.shape[0])      
ax.barh(ind, df['EndUse_91_1.0'], color='#FFFF00')
ax.barh(ind, df['EndUse_91_nan'], color='#FFFF00')
ax.barh(ind, df['EndUse_80_1.0'], color='#0070C0')
ax.barh(ind, df['EndUse_80_nan'], color='#0070C0')
plt.show()

在看到tcaswell的评论后已编辑为使用left kwarg.

Edited to use left kwarg after seeing tcaswell's comment.

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plot_chart(df, fig, ax)
ind = arange(df.shape[0])      
ax.barh(ind, df['EndUse_91_1.0'], color='#FFFF00')
lefts = df['EndUse_91_1.0']
ax.barh(ind, df['EndUse_91_nan'], color='#FFFF00', left=lefts)
lefts = lefts + df['EndUse_91_1.0']
ax.barh(ind, df['EndUse_80_1.0'], color='#0070C0', left=lefts)
lefts = lefts + df['EndUse_91_1.0']
ax.barh(ind, df['EndUse_80_nan'], color='#0070C0', left=lefts)
plt.show()

这似乎是正确的方法,但是如果没有特定条形的数据,它将失败,因为它正在尝试将nan添加到一个值中,然后返回nan.

This seems to be the right approach, but it fails if there is no data for a particular bar as it's trying to add nan to a value which then returns nan.

推荐答案

由于您使用的是熊猫,因此值得一提的是,您可以在本地进行堆积条形图:

Since you are using pandas, it's worth mentioning that you can do stacked bar plots natively:

df2.plot(kind='bar', stacked=True)

请参阅文档的可视化部分.

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

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