以下内容转自 数析学院,只节选了部分,有需要的同学可以直接查看原文
该 notebook 提供了本节使用的方法和代码:Rethinking the population pyramidhttp://www.randalolson.com/2015/ ... population-pyramid/,来自 Randal S. Olson http://www.randalolson.com/。
- %matplotlib inline
- import matplotlib.pyplot as plt
- import pandas as pd
- import numpy as np
- # 这是作者自定义的大部分绘图格式样式
- plt.style.use('https://gist.githubusercontent.com/rhiever
- /d0a7332fe0beebfdc3d5/raw
- /205e477cf231330fe2f265070f7c37982fd3130c
- /tableau10.mplstyle')
- age_gender_data = pd.read_csv('http://www.randalolson.com/wp-content
- /uploads/us-age-gender-breakdown.csv')
- age_gender_data.head()
1) 因变量不在 x 轴上
- fig = plt.figure(figsize=(15, 7))
- ax1 = fig.add_subplot(111)
- for (i, row) in age_gender_data.iterrows():
- plt.bar([i, i], [row['Females_2010'], -row['Males_2010']],
- color=['#CC6699', '#008AB8'], width=0.8, align='center',
- edgecolor='none')
-
- plt.xlim(-0.6, 20.6)
- plt.ylim(-12.1e6, 12.1e6)
- #plt.grid(False, axis='x')
- plt.xticks(np.arange(0, 21), age_gender_data['Age_Range'], fontsize=11)
- plt.yticks(np.arange(-12e6, 13e6, 2e6),
- ['{}m'.format(int(abs(x) / 1e6))
- if x != 0 else 0 for x in np.arange(-12e6, 13e6, 2e6)])
- plt.xlabel('Age group')
- plt.ylabel('Number of people (millions)')
- plt.savefig('pop_pyramid_rotated.pdf')
- ;
2) 无法直观比较两个类
- fig = plt.figure(figsize=(15, 7))
- ax1 = fig.add_subplot(111)
- for (i, row) in age_gender_data.iterrows():
- plt.bar([i - 0.2, i + 0.2], [row['Females_2010'], row['Males_2010']],
- color=['#CC6699', '#008AB8'], width=0.4, align='center', edgecolor='none')
-
- plt.xlim(-0.6, 20.6)
- plt.xticks(range(0, 21), age_gender_data['Age_Range'], fontsize=11)
- plt.grid(False, axis='x')
- plt.yticks(np.arange(0, 13e6, 1e6),
- ['{}m'.format(int(x / 1e6)) if x > 0 else 0 for x in np.arange(0, 13e6, 1e6)])
- plt.xlabel('Age group')
- plt.ylabel('Number of people (millions)')
- plt.savefig('pop_pyramid_grouped.pdf')
- ;
以上内容转自 数析学院,如需完整内容可以直接查看原文


雷达卡







京公网安备 11010802022788号







