2013-05-20 109 views
6

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

这是我的测试代码。

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

编辑使用left kwarg看到tcaswell的评论后。

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特定栏中没有数据失败。

+0

你需要使用'bottom' kwarg – tacaswell

+0

这就给我'TypeError:barh()为关键字参数'bottom''获得了多个值。好像我需要使用'left'。感谢您让我走上正轨。 –

+0

啊,对不起。 – tacaswell

回答

4

由于您使用的熊猫,这是值得一提的是,你可以做本地叠置条曲线:

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

visualisation section of the docs

6

下面是一个解决方案,虽然我确定必须有更好的方法来做到这一点。该series.fillna(0)部分替换任何nan以0

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'].fillna(0) 
ax.barh(ind, df['EndUse_91_nan'], color='#FFFF00', left=lefts) 
lefts = lefts + df['EndUse_91_1.0'].fillna(0) 
ax.barh(ind, df['EndUse_80_1.0'], color='#0070C0', left=lefts) 
lefts = lefts + df['EndUse_91_1.0'].fillna(0) 
ax.barh(ind, df['EndUse_80_nan'], color='#0070C0', left=lefts) 
plt.show() 
+0

看起来正确。如果要定期使用它,可能需要将重复的代码编写为循环/函数(请参阅我的答案) – tacaswell

3

作为一个侧面说明,你可以用在一个循环中通过重复代码了:

data_lst = [df['EndUse_91_1.0'], ..] 
color_lst = ["FFFF00", ..] 
left = 0 
for data, color in zip(data_lst, color_lst): 
    ax.barh(ind, data, color=color, left=left) 
    left += data 

模数据卫生

1

还有一个很好的答案,在这里堆栈溢出。 它附加在列表中绘制Hbars! Go to answer.

Other post's solution.