Home > front end >  How to set different colors on matplotlib bar graph based on the group of data?
How to set different colors on matplotlib bar graph based on the group of data?

Time:05-31

I have created this table:table

There are football players from every league whose overall rating is more than 80.

I also created a bar graph which looks like this:graph

Code I have written is this:

plt.figure(figsize=(15,5))
plt.bar(grouped.short_name,grouped.overall)
plt.title("football players with 80  rating")
plt.xticks(rotation=90)
plt.ylabel("overall rating")
plt.show()

But I want the graph to have columns of different colors based on the league player represents. For example: players from Seria A be Green, players from Bundesliga - Red and etc. I also want the graph to have legend which shows which color corresponds to which league. How can I do this?

CodePudding user response:

Try this code snippet.

This code allows you to set random colors to your barplot.

for i in range(0, len(grouped.short_name) 1):
    l.append(tuple(np.random.choice(range(0, 2), size=3)))
      
plt.bar(grouped.short_name, grouped.overall, color=l)

CodePudding user response:

I think this article might help you out https://www.tutorialspoint.com/how-to-change-the-color-of-a-single-bar-if-a-condition-is-true-matplotlib

  • Related