[英]Horizontal stacked bar chart in Matplotlib
我正在嘗試使用matplotlib
創建一個水平堆積條形圖,但我看不到如何使條形實際堆疊而不是從y軸開始。
這是我的測試代碼。
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。
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
的值。
這是一個解決方案,雖然我確信必須有更好的方法。 series.fillna(0)
部分用series.fillna(0)
替換任何nan
。
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()
作為旁注,您可以通過以下方式將重復代碼包裝在循環中:
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
模數據衛生
在Stack Overflow中有另一個很好的答案。 它會在附加到列表中時繪制Hbars! 去回答。
這是一個簡單的堆疊水平條形圖,顯示等待和運行時間。
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.