Gonzalo
Gonzalo

Reputation: 1114

bar plot does not respect order of the legend text in matplotlib

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:

enter image description here

Upvotes: 2

Views: 2145

Answers (2)

Serenity
Serenity

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()

enter image description here

Upvotes: 2

ImportanceOfBeingErnest
ImportanceOfBeingErnest

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])

enter image description here

You may also decide to invert the y axis.

ax = df.plot.barh()
ax.invert_yaxis()

enter image description here

Upvotes: 3

Related Questions