Python 和 Seaborn 的人口金字塔 [英] Population Pyramide with Python and Seaborn

查看:58
本文介绍了Python 和 Seaborn 的人口金字塔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建按性别分组的人口金字塔.不幸的是,我无法让它发挥作用.情节只是一张白色的图片,轴似乎以某种方式颠倒了.也许有人可以帮助我,谢谢.

将pandas导入为pd将 seaborn 作为 sns 导入导入 matplotlib.pyplot 作为 plt# 我从一个 csv 文件中读取这个测试数据testdata = pd.DataFrame({'年龄': [20, 20, 21, 21, 22, 22, 23, 23],'性别':[男"、女"、男"、女"、男"、女"、男"、女"]、'计数': [10, -12, 13, -10, 16, -14, 17, -16]});plt.figure(figsize=(13, 10), dpi=80)group_col = '性别'order_of_bars = testdata['age'].unique()[::-1]颜色 = [plt.cm.Spectral(i/float(len(testdata[group_col].unique()) - 1)) for i in range(len(testdata[group_col].unique()))]对于 c, group in zip(colors, testdata[group_col].unique()):barplot = sns.barplot(x='count', y='age', data=testdata.loc[testdata[group_col] == group, :], order=order_of_bars, color=c, label=group)plt.xlabel(计数")plt.ylabel(年龄")plt.yticks(字体大小=12)plt.title(金字塔", fontsize=22)plt.legend()plt.show()

解决方案

如果您正在寻找

I am trying to create a population pyramide grouped by gender. Unfortunately, I can't get this to work. The plot is just a white picture and the axes seem to be reversed somehow. Maybe someone can help me, thank you.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# I read this testdata from a csv file
testdata = pd.DataFrame({'age': [20, 20, 21, 21, 22, 22, 23, 23],
                'gender': ["male", "female", "male", "female", "male", "female", "male", "female"],
                'count': [10, -12, 13, -10, 16, -14, 17, -16]});


plt.figure(figsize=(13, 10), dpi=80)
group_col = 'gender'
order_of_bars = testdata['age'].unique()[::-1]
colors = [plt.cm.Spectral(i / float(len(testdata[group_col].unique()) - 1)) for i in range(len(testdata[group_col].unique()))]


for c, group in zip(colors, testdata[group_col].unique()):
    barplot = sns.barplot(x='count', y='age', data=testdata.loc[testdata[group_col] == group, :], order=order_of_bars, color=c, label=group)

plt.xlabel("Counts")
plt.ylabel("Age")
plt.yticks(fontsize=12)
plt.title("Pyramide", fontsize=22)
plt.legend()
plt.show()

解决方案

If you are looking for this population pyramid, let's try:

sns.barplot(data=testdata, x='count',y='age',
            hue='gender',orient='horizontal', 
            dodge=False)

Output:

这篇关于Python 和 Seaborn 的人口金字塔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆