簡體   English   中英

條形圖不符合matplotlib中圖例文本的順序

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

只是注意到圖例文本與繪圖欄的順序不同。 我希望看到“香蕉”成為傳說中的第一名。 是否可以糾正這種行為? 謝謝

我的代碼是:

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

我的圖:

在此處輸入圖片說明

圖例標簽實際上已正確訂購。 Matplotlib的垂直軸默認從底部開始並向上延伸。 因此,與圖例中一樣,藍色條形為第一。

您可以反轉圖例的句柄和標簽:

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

在此處輸入圖片說明

您也可以決定反轉y軸。

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

在此處輸入圖片說明

圖例處理程序的順序是按列順序選擇的,您必須以相反的順序對列的數據幀名稱進行排序(對列軸使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM