I.何をする?

次の解説を参考にPythonのMatplotlibのsubplotsの表示方法を学びます。

Take Full Control Over the Subplots in Matplotlib

II.Subplotsスペースの作成

# import libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# create two rows and three columns of rectangular space
fig, ax = plt.subplots(2, 3, sharex = 'col', sharey = 'row',
figsize = (9, 6))
fig.tight_layout(pad = 3.0)
# this is necessary for Visual Markdown
plt.show()

III.Subplotsへのアクセス

グラフは二次元のアレイに保存されています。

ax
## array([[<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>],
##        [<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>]], dtype=object)

それぞれのグラフに文字をいれます。

fig, ax = plt.subplots(2, 3, sharex = 'col', sharey = 'row',
                       figsize = (9,6))
fig.tight_layout(pad = 2)
for a in ax:
  for b in a:
    text = 'I am a plot'
    b.annotate(text, (0.3, 0.45), fontsize = 12)
plt.show()

for以下を解説します。

for a in axで何を取り出しているか確認します。

For loopsを復習します。For loopsのsyntaxは次です。

for <var> in <iterable>:
    <statement(s)>

Inの後に列がおかれます。列の項目を順にiterator取り出します。

For a in axで、列axから何を取り出しているのかを確認します。6つの表を順に取り出していることがわかります。

for a in ax:
  print(a)
  
## [<AxesSubplot:> <AxesSubplot:> <AxesSubplot:>]
## [<AxesSubplot:> <AxesSubplot:> <AxesSubplot:>]

この列axのiteratorsを表示します。それぞれのグラフの位置のようです。

for a in ax:
  for b in a:
    print(b)
## AxesSubplot(0.06625,0.55;0.251682x0.394537)
## AxesSubplot(0.383241,0.55;0.251682x0.394537)
## AxesSubplot(0.700231,0.55;0.251682x0.394537)
## AxesSubplot(0.06625,0.0858333;0.251682x0.394537)
## AxesSubplot(0.383241,0.0858333;0.251682x0.394537)
## AxesSubplot(0.700231,0.0858333;0.251682x0.394537)

サンプルデータを読み込みます。

import pandas as pd
df = pd.read_csv('https://pastebin.com/raw/nWkAe1qR')
df.head()
##    id  english  japanese nationality  department  year gender
## 0   1     17.8      75.6    japanese  literature     1   male
## 1   2     64.4      53.3       nepal  literature     1   male
## 2   3     86.7      31.1       nepal  literature     1   male
## 3   4     60.0      62.2   indonesia  literature     1   male
## 4   5     42.2      80.0    japanese  literature     1   male

グラフを作成します。

ax[行、列]でグラフの位置を指定します。それぞれ0から始まります。

例えば、ax[1, 1]は2行目の左から2つ目を意味しています。

英語と数学の得点のscatter plot、国籍別人数のpie plot、英語の得点のヒストグラムを描くスクリプトは次です。

fig, ax = plt.subplots(2, 3, figsize = (15, 10))
fig.tight_layout(pad = 2)
ax[0, 0].scatter(df['english'], df['japanese'])
df['english'].hist(ax = ax[1, 1])
df.groupby('nationality')['nationality'].count().plot(ax = ax[0, 1], kind='pie', colors = ['lightgreen', 'coral', 'pink', 'violet', 'skyblue'])
plt.show()

To be continued.