[英]How to build a population pyramid with pandas dataframe
How to plot a population pyramid based on the following starting dataframe?如何根据以下起始数据框绘制人口金字塔?
Age Gender Count
0 50-45 years male 4
1 50-45 years female 5
2 55-65 years male 6
3 55-65 years female 7
4 65-70 years male 11
5 65-70 years female 12
I tried the following, Population Pyramid with Python and Seaborn , but the resulting plot looks strange:我尝试了以下内容,带有 Python 和 Seaborn 的人口金字塔,但结果图看起来很奇怪:
import pnadas as pd
import seaborn as sns
# data
data = {'Age': ['50-45 years', '50-45 years', '55-65 years', '55-65 years', '65-70 years', '65-70 years'],
'Gender': ['male', 'female', 'male', 'female', 'male', 'female'], 'Count': [4, 5, 6, 7, 11, 12]}
df = pd.DataFrame(data)
# plot
sns.barplot(data=df, x='Count', y='Age',
hue='Gender', orient='horizontal',
dodge=False)
I think the problem is that my age is a string.我认为问题在于我的年龄是一个字符串。
'Count'
for both 'Gender'
groups is positive, so with dodge=False
, the 'Female'
bars are drawn on top of the 'Male'
bars.与链接的问题不同,两个'Gender'
组的'Count'
都是正数,因此使用dodge=False
, 'Female'
条形图绘制在'Male'
条形图之上。.loc
and Boolean selection.使用.loc
和布尔选择将组之一转换为负值。# convert male counts to negative
df.loc[df.Gender.eq('male'), 'Count'] = df.Count.mul(-1)
# plot
sns.barplot(data=df, x='Count', y='Age', hue='Gender', orient='horizontal', dodge=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.