LoginSignup
5
5

More than 5 years have passed since last update.

Pythonで積み上げ棒グラフを並べてみる

Last updated at Posted at 2018-06-07

Pythonで統計データを扱う(というかグラフを描く)練習の続き。

積み上げ棒グラフを複数並べる方法について調べてみた。

積み上げ棒グラフの描画についてはこちら,並べて表示する方法についてはこちらを参考にさせていただきました。

データはe-Statより,

  • 統計名:社会生活基本調査 平成28年社会生活基本調査 調査票Aに基づく結果 生活行動に関する結果 生活行動編(全国) スポーツ
  • 表番号:15-7

のうち,野球とサッカーの男女・年齢別競技人口を使用。

年齢 野球男 野球女 サッカー男 サッカー女
15~19歳 46 13 44 7
20~24歳 341 111 281 100
25~29歳 541 147 482 128
30~34歳 485 177 532 102
35~39歳 622 186 515 159
40~44歳 697 229 514 145
45~49歳 549 77 227 52
50~54歳 296 47 117 17
55~59歳 199 13 61 11
60~64歳 93 16 35 10
65~69歳 145 21 39 7
70~74歳 96 13 25 7
75~79歳 58 7 12 1
80~84歳 22 2 2 2
85歳以上 1 1 0 0
Python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'IPAPGothic'

df = pd.read_table('sports.tsv', index_col=0)
bb = df['野球男']
bg = df['野球女']
sb = df['サッカー男']
sg = df['サッカー女']

w = 0.3 # 棒グラフの幅
ind = np.arange(len(df)) # x方向の描画位置を決定するための配列

# 野球人口
plt.bar(ind, bb, width=w, color='b', label='野球:男')
btm = np.array(bb.values) # 積み上げ(底上げ)のためにデータを取得
plt.bar(ind, bg, width=w, bottom=btm, color='c', label='野球:女') # 男性データの上に積み上がるようbottomを設定

# サッカー人口
plt.bar(ind+w, sb, width=w, color='r', label='サッカー:男')
btm = np.array(sb.values)
plt.bar(ind+w, sg, width=w, bottom=btm, color='orange', label='サッカー:女') # グラフ幅の分だけ右にずらして描画

plt.subplots_adjust(bottom=0.2) # 下余白調整(default=0.1)
plt.xticks(ind+w/2, df.index, rotation=90) # x軸目盛の描画位置が2本の棒の間にくるように調整
plt.ylabel('人数(千人)')
plt.legend()
plt.show()

できあがったグラフはこちら。
sports.png

  • 色のせいか,ごちゃごちゃして見づらいグラフになる
  • もっと簡単な方法は無いものか
  • やっぱり40歳越えるとサッカーは厳しいのか

追記

わざわざbtmなんて変数用意しなくてもよかった。

Python
# 野球人口
plt.bar(ind, bb, width=w, color='b', label='野球:男')
plt.bar(ind, bg, width=w, bottom=bb.values, color='c', label='野球:女')

# サッカー人口
plt.bar(ind+w, sb, width=w, color='r', label='サッカー:男')
plt.bar(ind+w, sg, width=w, bottom=sb.values, color='orange', label='サッカー:女')
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5