Home > Software design >  How to set different colors for specific columns in matplotlib bar chart?
How to set different colors for specific columns in matplotlib bar chart?

Time:05-31

I created a bar chart of 10 football clubs with highest and 10 with the lowest FIFA ratings. I plotted both on the same figure this way:

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

The result is this: [image]

But I want to top 10 and bottom 10 columns to have different colors. For example first 10 columns to be red and last 10 blue color. Also I want my chart to have a legend that explains which color corresponds to which. I hope there is a way of doing this.

CodePudding user response:

You can iterate over the bars and use set_color() to update the color manually.

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

CodePudding user response:

You could use color parameter in plot

unioned.plot(kind="bar",x="club_name",y="overall",xlabel="",figsize=(15,5), color=[*['red']*10, *['green']*10])

not very nice to make a list like that for color, but if you know that there is always 20 clubs in plot then it will do the trick

  • Related