[英]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.
Matplotlib的垂直轴默认从底部开始并向上延伸。 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. 您也可以决定反转y轴。
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). 图例处理程序的顺序是按列顺序选择的,您必须以相反的顺序对列的数据帧名称进行排序(对列轴使用
reindex_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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.