![](/img/trans.png)
[英]How to change/set multiple bar colors in matplotlib bar chart (python)
[英]How to set different colors for specific columns in matplotlib bar chart?
我創建了一個條形圖,其中包含 10 個最高的足球俱樂部和 10 個最低的 FIFA 評分。 我以這種方式將兩者繪制在同一個圖上:
grouped_top=df.groupby("club_name")["overall"].mean().reset_index().sort_values("overall",ascending=False).head(10)
grouped_bottom=df.groupby("club_name")["overall"].mean().reset_index().sort_values("overall",ascending=False).tail(10)
unioned=pd.concat([grouped_top,grouped_bottom])
unioned.plot(kind="bar",x="club_name",y="overall",xlabel="",figsize=(15,5))
plt.show()
結果是這樣的:
但我希望前 10 列和后 10 列具有不同的顏色。 例如前 10 列為紅色,最后 10 列為藍色。 另外我希望我的圖表有一個圖例來解釋哪種顏色對應於哪種顏色。 我希望有辦法做到這一點。
您可以遍歷條形圖並使用set_color()手動更新顏色。
import matplotlib
import matplotlib.pyplot as plt
ax = unioned.plot(kind="bar", x="club_name", y="overall", xlabel="", figsize=(15,5))
# Highest ratings
for i in range(0, 10):
ax.get_children()[i].set_color("red")
# Lowest ratings
for i in range(10, 20):
ax.get_children()[i].set_color("blue")
legends = [
matplotlib.patches.Patch(color="red", label="Highest ratings"),
matplotlib.patches.Patch(color="blue", label="Lowest ratings"),
]
ax.legend(handles=legends, prop={"size": 20})
plt.show()
您可以在plot
中使用color
參數
unioned.plot(kind="bar",x="club_name",y="overall",xlabel="",figsize=(15,5), color=[*['red']*10, *['green']*10])
為顏色列出這樣的列表並不是很好,但如果你知道情節中總是有 20 個俱樂部,那么它就可以了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.