如何为matplotlib条形图中的特定列设置不同的颜色?

How to set different colors for specific columns in matplotlib bar chart?

我创建了 FIFA 评分最高的 10 个足球俱乐部和最低的 10 个足球俱乐部的条形图。 我以这种方式将两者绘制在同一个图形上:

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 个俱乐部,那么它就可以了