首页 > 解决方案 > 使用 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列的总和对水平条进行降序排序?

标签: pythondataframematplotlib

解决方案


您可以使用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))

输出:

在此处输入图像描述


推荐阅读