Python Matplotlib 中的水平堆积条形图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16653815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Horizontal stacked bar chart in Matplotlib
提问by Jamie Bull
I'm trying to create a horizontal stacked bar chart using matplotlibbut I can't see how to make the bars actually stack rather than all start on the y-axis.
我正在尝试使用创建一个水平堆叠条形图,matplotlib但我看不到如何使条形实际堆叠而不是全部从 y 轴开始。
Here's my testing code.
这是我的测试代码。
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()
Edited to use leftkwarg after seeing tcaswell's comment.
left在看到 tcaswell 的评论后编辑使用kwarg。
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()
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 nanto a value which then returns nan.
这似乎是正确的方法,但如果没有特定条形的数据,它会失败,因为它试图添加nan到一个值,然后返回nan.
采纳答案by Andy Hayden
Since you are using pandas, it's worth mentioning that you can do stacked bar plots natively:
由于您使用的是熊猫,值得一提的是,您可以在本机上制作堆叠条形图:
df2.plot(kind='bar', stacked=True)
See the visualisation section of the docs.
回答by Jamie Bull
Here's a solution, although I'm sure there must be a better way of doing it. The series.fillna(0)part replaces any nanwith 0.
这是一个解决方案,尽管我确信必须有更好的方法来做到这一点。该series.fillna(0)部分将 any 替换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()
回答by tacaswell
As a side note, you can wrap the repetitive code up in a loop via:
作为旁注,您可以通过以下方式将重复代码包装在一个循环中:
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
modulo data-sanitation
模数数据卫生
回答by Arthur Zennig
There was another good answer, here in Stack Overflow. It draws the Hbars while appending in a list! Go to answer.
还有另一个很好的答案,在 Stack Overflow 上。它在附加到列表中时绘制 Hbars! 去回答。


回答by vicR
Its also possible (and very easy) to just element wise add all elements by using Mapand the add operator. As already answered in the question Element-wise Addition of 2 Lists in Python?. Or just use numpy array.
也可以(并且非常容易)通过使用Map和元素明智地添加所有元素add operator。正如Python中的Element-wise Addition of 2 Lists问题中已经回答的那样?. 或者只是使用 numpy 数组。
回答by NathanH
Here's a simple stacked horizontal bar graph displaying wait and run times.
这是一个简单的堆叠水平条形图,显示等待和运行时间。
from datetime import datetime
import matplotlib.pyplot as plt
jobs = ['JOB1','JOB2','JOB3','JOB4']
# input wait times
waittimesin = ['03:20:50','04:45:10','06:10:40','05:30:30']
# converting wait times to float
waittimes = []
for wt in waittimesin:
waittime = datetime.strptime(wt,'%H:%M:%S')
waittime = waittime.hour + waittime.minute/60 + waittime.second/3600
waittimes.append(waittime)
# input run times
runtimesin = ['00:20:50','01:00:10','00:30:40','00:10:30']
# converting run times to float
runtimes = []
for rt in runtimesin:
runtime = datetime.strptime(rt,'%H:%M:%S')
runtime = runtime.hour + runtime.minute/60 + runtime.second/3600
runtimes.append(runtime)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.barh(jobs, waittimes, align='center', height=.25, color='#00ff00',label='wait time')
ax.barh(jobs, runtimes, align='center', height=.25, left=waittimes, color='g',label='run time')
ax.set_yticks(jobs)
ax.set_xlabel('Hour')
ax.set_title('Run Time by Job')
ax.grid(True)
ax.legend()
plt.tight_layout()
#plt.savefig('C:\Data\stackedbar.png')
plt.show()



