簡體   English   中英

使用 Python matplotlib 訂購單杠

[英]Ordering Horizontal Bars Using Python matplotlib

我有以下代碼使用 python 和 matplotlib 顯示水平條形圖。

plt.style.use('seaborn')
plt.rcParams['figure.figsize'] = (16.0, 10.0)

category_names = ['ProjectA', 'ProjectB', 'ProjectC', 'ProjectD', 'ProjectE']
results = {'Passed': [3, 4, 32, 6, 50],
           'Failed': [2, 9, 60, 4, 68]}

df = pd.DataFrame(results, index=category_names)
ax = df.plot.barh(stacked=True, cmap='tab10', figsize=(16, 10))

for p in ax.patches:
    left, bottom, width, height = p.get_bbox().bounds
    if width > 0:
         ax.annotate(f'{width:0.0f}', xy=(left+width/2, bottom+height/2), ha='center', va='center')

這將為我提供以下圖表:

在此處輸入圖像描述

現在我的問題是,如何根據PassedFailed列的總和對水平條進行降序排序?

您可以使用argsort來獲取條的順序,並iloc

orders = np.argsort(df.sum(1))  # chain with `[::-1]` if want the reverse order

ax = df.iloc[orders].plot.barh(stacked=True, cmap='tab10', figsize=(16, 10))

Output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM