Search code examples
seaborndata-visualizationbar-chart

Seaborn grouped Bar plot


I am trying to create visualizations for recent commonwealth medal tally dataset. I would like to create a grouped bar chart of top ten countries by total number of medals won. Y axis = total x axis = Country name How can I divide totals into three bars consisting of no of : gold, Silver,Bronze medals won by each country?

I created one using excel, but don't know how to do it using seaborn

P.S. I have already tried using a list of columns for hue.

df_10  =  df.head(10)
sns.barplot(data  = df_10, x  = 'team' , y = 'total' , hue = df_10[["gold" , 
"silver","bronze"]].apply(tuple , axis = 1) )

Here is the chart that I created using excel:

enter image description here


Solution

  • To plot the graph, you will need to change the dataframe to the format that will allow for easy plotting. One of the ways to do this is using dataframe.melt(). The method used by you may not work... Once the data is in a format that seaborn understands easily, plotting will become simple. As you have not provided the format for df_10, I have assumed the data to have 4 columns - Country, Gold, Silver and Bronze. Below is the code...

    ## Use melt using Country as ID and G, S, B as the rows for values
    df_10 = pd.melt(df_10, id_vars=['Country'], value_vars=['Gold', 'Silver', 'Bronze'])
    df_10.rename(columns={'value':'Count', 'variable':'Medals'}, inplace=True) ##Rename so the plot has informative texts
    fig, ax=plt.subplots(figsize=(12, 7))  ## Set figure size
    ax=sns.barplot(data=df_10, x='Country', y='Count', hue='Medals') ## Plot the graph
    

    enter image description here