LoginSignup
2
5

More than 3 years have passed since last update.

seabornとmatplotlibのfigureとaxesを使って複数のグラフを描く

Last updated at Posted at 2020-11-01

概要

matplotlibをドキュメントを読まずに場当たり的に使っていると、
イマイチよく分からないままになるfigureとaxesをさらっと分かった気になる記事
(分かるわけではない)

どうしてこれを書いたか

ちょっとドキュメントを読んだら分かった気になったので、
他の人にも分かった気になって欲しかったから。

ちゃんと理解するには

内容

前提

以下は省略して書きます。

import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt

まずはじめに

figureとaxesはこんな関係。
figureが描画領域全体で、axesがグラフの描画領域

  • グラフの描画領域が1つの場合
    pic1.png

  • グラフの描画領域が2つ(1行2列)の場合
    pic2.png

からっぽのグラフの描画領域を1行2列の配置で2つ作ってみる

# サイズが8,4の描画領域と1行2列のグラフの描画領域を作る
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8,4))

# figureのタイトルを設定する
fig.suptitle("figure_title")

# 1番目の描画領域にタイトルを設定する
ax[0].set_title("axes0_title")

# 2番目の描画領域にタイトルを設定する
ax[1].set_title("axes1_title")

実行結果
スクリーンショット 2020-11-01 21.15.23.png

グラフを描画してみる

# 10000個の数字を作る
norm_arr = np.random.randn(10000)

# サイズが6,3の描画領域と1行2列のグラフの描画領域を作る
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(6,3))

# figureのタイトルを設定する
fig.suptitle("figure_title")

# 1番目のaxesにタイトルを設定する
ax[0].set_title("axes0")

# 1番めのaxesにグラフを書く
ax[0].hist(norm_arr)

# 2番目のaxesにタイトルを設定する
ax[1].set_title("axes1")

# 2番目のaxesにseabornでグラフを書く
sns.histplot(norm_arr, ax=ax[1])

実行結果
スクリーンショット 2020-11-01 21.21.37.png

重ねて描画してみる

# 前項のコードの末尾に以下のコードを追加する
x_scat = np.random.randn(100)
y_scat = np.random.randint(low=100, high=500, size=(1,100))
ax[1].scatter(x_scat, y_scat) #1番目のaxesに散布図を書く

実行結果
実行結果2番目のaxesに重ねて描画されているのが分かる。
スクリーンショット 2020-11-01 21.59.04.png

おわり

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