Reputation: 1114
Just noticed that the legend text doesnt have the same order as the plot bars. I would expect to see the "Banana" in first place of the legend. Is it possible to correct such behavior? Thanks
My code is:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({"Apple" : [2,3,4,1], "Banana" : [4,2,1,2]})
ax = df.plot.barh()
ax.legend()
plt.show()
And my graph:
Upvotes: 2
Views: 2145
Reputation: 36685
Order of legend handlers is selected by columns ordering, you have to sort columns' names of dataframe in reversed order (use reindex_axis
for column axis).
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({"Apple" : [2,3,4,1], "Banana" : [4,2,1,2]})
df = df.reindex_axis(reversed(sorted(df.columns)), axis = 1)
ax = df.plot.barh()
ax.legend()
plt.show()
Upvotes: 2
Reputation: 339430
The legend labels are actually ordered correctly. Matplotlib's vertical axes by default start at the bottom and reach upwards. Hence the blue bars come first, just as in the legend.
You can invert the legend handles and labels:
h, l = ax.get_legend_handles_labels()
ax.legend(h[::-1], l[::-1])
You may also decide to invert the y axis.
ax = df.plot.barh()
ax.invert_yaxis()
Upvotes: 3