gpt4 book ai didi

python - 条形图不尊重 matplotlib 中图例文本的顺序

转载 作者:行者123 更新时间:2023-11-28 22:23:39 25 4
gpt4 key购买 nike

刚刚注意到图例文本与绘图条的顺序不同。我希望在传说中看到“香蕉”。是否有可能纠正这种行为?谢谢

我的代码是:

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

还有我的图表:

enter image description here

最佳答案

图例标签实际上是正确排序的。 Matplotlib 的垂直轴默认从底部开始向上延伸。因此,蓝条排在第一位,就像图例中一样。

您可以反转图例句柄和标签:

h, l = ax.get_legend_handles_labels()
ax.legend(h[::-1], l[::-1])

enter image description here

您也可以决定反转 y 轴。

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

enter image description here

关于python - 条形图不尊重 matplotlib 中图例文本的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46908085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com