0

I've built this grouped bar graph that shows the value of each column of these 5 countries, I took the data table from the Global Gender Gap Index. enter image description here

This is my code:

import matplotlib.pyplot as plt
import pandas as pd
plt.rcParams.update({'font.size': 22})

df = pd.read_html(
    "https://worldpopulationreview.com/country-rankings/gender-equality-by-country", index_col=0)[1]
for x in list(df):
    df[x] = df[x].str.rstrip('%').astype('float') / 100.0
df = df.rename(columns={'Economic Opp.': 'Economic Opportunity'})

with plt.style.context('dark_background'):
    df.loc[{"China", "India", "United States", "Indonesia", "Pakistan"},
           "Economic Opportunity": "Political Power"].transpose().plot(kind="bar", figsize=(20, 10), width=0.5, align='center', linewidth=8, edgecolor='black')
    plt.xticks(rotation=360)
    plt.title(
        "The 4 Gender Equality parameters in the 5 most populated countries on Earth")
    plt.show()

I would like to add a line that shows the world's mean of each parameter(or column), it should be similar to this: enter image description here

I tried to add lines manually using plt.hlines:

...
with plt.style.context('dark_background'):
    ...
    plt.hlines(y=0.954187, xmin=1.2, xmax=1.5, color='orange',
               linestyle='dashed', linewidth=5)

But I wasn't able to get the result I wanted. Maybe it's because the x axis doesn't have numerical value.

Jock
  • 388
  • 2
  • 12

1 Answers1

2

Although the X-axis is categorical, the xmin starts off from zero. More information here. You can add this piece of code between your plt.ticks and plt.title. Note that I am skipping the first column as it is GEI 2021, which I guess you are not using...

    for i, col in enumerate(df.columns):
        if i == 0: #Skip GEI 2021
            pass
        else:
            myMean = df[col].mean() #Get mean for the col
            #i is the center of X-axis. I am using 0.5 length, adjust as you see fit
            plt.hlines(y=myMean, xmin=(i - 1.25), xmax=(i - 0.75), color='orange', linestyle='dashed', linewidth=5) 

Output Graph

enter image description here

Redox
  • 9,321
  • 5
  • 9
  • 26