1

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?

beridzeg45
  • 246
  • 2
  • 11
  • Could you perhaps post a raw version of a small sample of your data? Not in image format. – Itai Dagan May 31 '22 at 08:39
  • check out the existed so post https://stackoverflow.com/questions/57340415/matplotlib-bar-plot-add-legend-from-categories-dataframe-column and if you still can't figure out, post your data as @ItaiDagan mentions about. – paulyang0125 May 31 '22 at 09:00

4 Answers4

2

I'd use seaborn and use the hue parameter. You need to make sure your player short names are unique.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = {'league_name':['A','A','A','B','C','C','C'],
        'club_name':['Club 1','Club 1', 'Club 1','Club 2', 'Club 3', 'Club 3', 'Club 3'],
        'short_name':['Joe','Jon','Jack','Ryan','Peter','Steve','Paul'],
        'overall':[83,88,87,90,87,93,81]}

df = pd.DataFrame(data)




ax = sns.barplot(x='short_name', y='overall', data=df, hue='club_name', dodge=False)
plt.title("football players with 80+ rating")
plt.xticks(rotation=90)
plt.ylabel("overall rating")
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)

enter image description here

chitown88
  • 27,527
  • 4
  • 30
  • 59
2

Thanks for the responses. After some research I came up with this answer:

import random
leagues=grouped.league_name.unique()
plt.figure(figsize=(14,5))
for l in leagues:
    rgb = (random.random(), random.random(), random.random())
    plt.bar(grouped[grouped.league_name==l].short_name,grouped[grouped.league_name==l].overall,color=[rgb],label=l)
    plt.xticks(rotation=90)
    plt.title("players with 80+ rating")
    plt.legend(bbox_to_anchor=(1,1),fontsize=6)
    def value_labels(y):
        for i in range(len(y)):
            plt.text(i,round(y.iloc[i]),round(y.iloc[i]),size=7,ha="center",va="bottom",rotation=0)
    value_labels(grouped.overall)
plt.show()

Here is the result:

image

It comes with some kind of alert which I don't understand. I got the desired result though.

RiveN
  • 2,595
  • 11
  • 13
  • 26
beridzeg45
  • 246
  • 2
  • 11
0

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)
Harsh gupta
  • 180
  • 7
0

You should get the list of bars when plotting the graph, then change the bar color according to the league name.

plt.figure()
bars = plt.bar(short_name, overall)

for i, bar in enumerate(bars):
    if "English" in league_name[i]:
        bar.set_color('r')

plt.show()
Itai Dagan
  • 285
  • 2
  • 11