向分组的条形图添加线
我已经构建了这个分组的条形图,显示了这5个国家/地区的每一列的值,我从全球性别差距索引。
这是我的代码:
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()
我想添加一行,显示每个参数(或列)的世界平均值,它应该与以下方式相似:
我尝试使用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)
但是我无法获得所需的结果。也许是因为X轴没有数值值。
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.
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:
...
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尽管X轴是分类的,但Xmin从零开始。更多信息。您可以在
plt.ticks
和plt.title
之间添加此代码。请注意,我正在跳过第一列,因为它是gei 2021
,我想您没有使用...输出图
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
andplt.title
. Note that I am skipping the first column as it isGEI 2021
, which I guess you are not using...Output Graph