简体   繁体   English

向分组条形图添加线

[英]Adding lines to a grouped bar graph

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 .我已经建立了这个分组条形图,显示了这 5 个国家的每一列的值,我从全球性别差距指数中获取了数据表。 在此处输入图像描述

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:我想添加一行显示每个参数(或列)的世界平均值,它应该类似于: 在此处输入图像描述

I tried to add lines manually using plt.hlines:我尝试使用 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.也许是因为 x 轴没有数值。

Although the X-axis is categorical, the xmin starts off from zero.尽管 X 轴是分类的,但 xmin 从零开始。 More information here .更多信息在这里 You can add this piece of code between your plt.ticks and plt.title .您可以在plt.ticksplt.title之间添加这段代码。 Note that I am skipping the first column as it is GEI 2021 , which I guess you are not using...请注意,我跳过第一列,因为它是GEI 2021 ,我猜您没有使用...

    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输出图

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM