Matplotlib中的水平堆积条形图
问题描述:
我正在尝试使用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
特定栏中没有数据失败。
答
由于您使用的熊猫,这是值得一提的是,你可以做本地叠置条曲线:
df2.plot(kind='bar', stacked=True)
答
下面是一个解决方案,虽然我确定必须有更好的方法来做到这一点。该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
答
作为一个侧面说明,你可以用在一个循环中通过重复代码了:
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
模数据卫生
答
它也有可能(并且很容易),只是元素方式使用Map
和add operator
添加的所有元素。正如已在问题Element-wise Addition of 2 Lists in Python?中回答的那样。或者只是使用numpy数组。
你需要使用'bottom' kwarg – tacaswell
这就给我'TypeError:barh()为关键字参数'bottom''获得了多个值。好像我需要使用'left'。感谢您让我走上正轨。 –
啊,对不起。 – tacaswell