LoginSignup
5
8

More than 3 years have passed since last update.

【グラフ描画】複数系列の棒グラフをmatplotlibとseabornで書いてみた

Last updated at Posted at 2020-05-10

はじめに

複数系列の棒グラフの描画をmatplotlibとseabornで比較してみました。

結論から言うと、seabornは便利ですねという記事です

  • 環境
    • Windows-10-10.0.18362-SP0
    • Python 3.7.6
    • pip 19.3.1
    • pandas 1.0.3
    • matplotlib 3.1.2
    • seaborn 0.10.0
    • numpy 1.18.1

描画するグラフ

左側がmatplotlib,右側がseabornです。グラフだけ見ると同じですが、これらを描画するまでがseabornは楽です。
棒の色は同じ色を指定していますが、seabornのほうがちょっと淡いですね。こういうのももしかしたら設定がどこかにあるんでしょうか・・・
グラフを描画してみた.png

描画の流れ

上の棒グラフを描画するまでの流れです。

ライブラリをインストール

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from io import StringIO
import numpy as np
%matplotlib inline

DataFrameを作成する

data = ('人数,性別,年齢\n'
       '58,男性,18歳\n'
       '25,男性,19歳\n'
       '42,男性,20歳\n'
       '60,女性,18歳\n'
       '42,女性,19歳\n'
       '70,女性,20歳\n' 
       )
df = pd.read_csv(StringIO(data), dtype={'人数':'int32'})
print(df)

人数 性別 年齢
58 男性 18歳
25 男性 19歳
42 男性 20歳
60 女性 18歳
42 女性 19歳
70 女性 20歳

グラフを描画する

plt.rcParams['font.family'] = 'Yu Gothic' #Yu Gothicをデフォルト設定で日本語文字化けを回避
plt.rcParams['font.size'] = 20 #デフォルトのフォントサイズを設定

fig,ax = plt.subplots(1, 2, figsize=(24,10)) #1行、2列で横24インチ、縦10インチの描画スペースを作成


#matplotlibでの棒グラフ描画はdfのデータをちょっと分けます
labels = list(df['年齢'].unique()) #X軸のラベルに相当する場所をdfからリスト化
number_male = list(df['人数'].loc[0:2]) #dfの上から3行の人数の数値(男性の数値)をリスト化
number_female = list(df['人数'].loc[3:5]) #dfの下から3行の人数の数値(女性の数値)をリスト化
left = np.arange(len(number_male)) #X軸のラベルを貼り付ける座標を指定する用
print(left) #leftの中身は [0 1 2]
width = 0.4 #複数系列のグラフの場合はX軸ラベルの座標がleftのみだとずれるので、補正分


#matplotlibで棒グラフ
ax[0].bar(x=left, height=number_male, width=width, align='center', color='royalblue') #男性部分の棒グラフを追加
ax[0].bar(x=left+width, height=number_female, width=width, align='center', color='tomato') #女性部分の棒グラフを追加
ax[0].set_xticks(left + width / 2) #18歳、19歳、20歳部分の軸の位置を指定
ax[0].set_xticklabels(labels=labels) #"18歳、19歳、20歳"を描画するように指定
ax[0].set_xlabel('年齢') #X軸のラベル
ax[0].set_ylabel('人数') #Y軸のラベル
ax[0].legend(list(df['性別'].unique()), title='性別', loc='upper right') #凡例の男性、女性、タイトルを性別、位置を右上へ設定
ax[0].set_title('matplotlibで棒グラフ', size=30) #タイトルを設定


#seabornで棒グラフ
sns.barplot(data=df, x='年齢', y='人数', hue='性別', ax=ax[1], palette={'男性':'royalblue','女性':'tomato'}) #data=dfと指定して、XとYを設定、hue='性別'とすることで性別別で分けてくれる
ax[1].legend(loc='upper right', title='性別') #凡例のタイトル、位置を右上へ設定
ax[1].set_title('seabornで棒グラフ', size=30) #タイトルを設定


plt.savefig('グラフを描画してみた.png', bbox_inches='tight', pad_inches=0.3) #描画した画像を保存
plt.show() #描画

これでこちらの棒グラフ が描画されます。

行数
matplotlib 8
seaborn 3

seabornのほうが見るからに楽に描画できます!コードは凡例とタイトルで2行なので、1行だけで複数系列の棒グラフを書けますね。

5
8
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
8