Matplotlib, horizontal bar chart (barh) is upside-down

I believe the joint wrong order of groups and subgroups boils down to a single feature: that the y axis increases upwards, as in a usual plot. Try reversing the y axis of your axes as in this pandas-less example:

import numpy as np
import matplotlib.pyplot as plt

x = range(5)
y = np.random.randn(5)

# plot 1: bar
plt.figure()
plt.bar(x, y)

# plot 2: barh, wrong order
plt.figure()
plt.barh(x, y)

# plot 3: barh with correct order: top-down y axis
plt.figure()
plt.barh(x, y)
plt.gca().invert_yaxis()

plt.show()

Specifically for pandas, pandas.DataFrame.plot and its various plotting submethods return a matplotlib axes object, so you can invert its y axis directly:

ax = df.plot.barh()  # or df.plot(), or similar
ax.invert_yaxis()

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)