简体   繁体   中英

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:

在此处输入图片说明

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

在此处输入图片说明

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM