【问题标题】:How to build a population pyramid with pandas dataframe如何使用 pandas 数据框构建人口金字塔
【发布时间】:2021-12-20 04:42:32
【问题描述】:

如何根据以下起始数据框绘制人口金字塔?

           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

我尝试了以下Population Pyramid with Python and 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)

我认为问题在于我的年龄是一个字符串。

【问题讨论】:

    标签: python pandas matplotlib seaborn bar-chart


    【解决方案1】:
    • 与链接的问题不同,'Count' 对于两个 'Gender' 组都是正数,因此对于 dodge=False'Female' 条将绘制在 'Male' 条的顶部。
    • 使用.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)
    

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      相关资源
      最近更新 更多