Ordering Horizontal Bars Using Python matplotlib

Viewed 175

I have the following code to display a horizontal bar chart using python and the 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')

This will get me the following chart:

enter image description here

Now my question is, how do I order the horizontal bars descending based on the sum of Passed and Failed columns?

1 Answers

You can use argsort to get the order of the bars, and 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:

enter image description here

Related