0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【matplotlib】 figureとaxesの関係について

Last updated at Posted at 2022-10-05

はじめに

matplotlib に出てくる figure と axes の関係について、深くまで理解せずあいまいな解釈でコードを書いていたので根本的に理解することを目的にこの記事を残す 

figureとaxes

figure は描画領域で、axes は個々のグラフである。
figure は「fig」, axes は「ax」と略されることが多い。

figureオブジェクト

  • グラフの描画領域全体のこと。ここにさまざまなグラフ(axes)を描いていく。
  • すべてのプロット要素の最上位コンテナである。
  • グラフとして保存するときはfigure単位になる。大抵は figure 1つで事足りることが多い。
# 描画領域を生成する
fig = plt.figure()

axesオブジェクト

  • 一般的な英単語で使用される場合は「軸」という意味であるが、matplotlibにおいては1つのグラフのようなものと考えるとよい
  • figureの中に複数のaxesを設定することができる

axesの読み方は「アクシーズ」で、axis(軸)の複数形である。

描画領域をグリッド状に分割する

matplotlib において、一つの figure の中に複数の axes があるとき、それらを subplot という。figure を規則正しいグリッド状に分割して、その分割した一つ一つの領域に axes を追加していく。

axes を1つずつ作成 or 1度に全部作成

  • m × n 行列で分割した領域の中から位置を1つ指定し、axes を作成する場合
2x2 にグリッド上に分割した場合の index=3 の位置に axes を作成する。 引数に行数列数及び何番目かを指定できる。
plt.subplot(2, 2, 3)
plt.plot(x, y)

figure クラスの figure.add_subplot() でも同じことができる。

fig = plt.figure()
ax = fig.add_subplot(2, 2, 3)
ax.plot(x, y)


  • m × n 行列で分割した領域のすべてに axes を作成する場合
# ax には、axesオブジェクトの 2×1 のnumpy配列が格納される。
fig, ax = plt.subplots(2, 1)  
ax[0].plot(x1, y1)     
ax[1].plot(x2, y2)

figure.subplots() でも同じことができる。

fig = plt.figure()
ax = fig.subplots(2, 1)
ax[0].plot(x1, y1)
ax[1].plot(x2, y2)

参考にしたサイト
https://pystyle.info/matplotlib-create-subplots/

グラフを表示するまでの流れ

人によって使い方や考え方は異なるが、大まかには以下の通りである。

  1. figure を生成する
  2. 生成した figureに axes を生成、配置する
  3. axes に描画データやグラフの詳細な情報、追加情報を設定する
  4. 表示したり、画像として保存したりする

引用:https://www.python.ambitious-engineer.com/archives/2680

まとめ

おおまかな流れの中における figure と axes の役割を知ることができた。それぞれの単語の役割に対して具体的なイメージが思い描けないとややこしく感じる部分でもあるので、今回は体系的に理解できるまで調べることができてよかった。matplotlibは今後の大学生活でも頻繁に使うライブラリなので、学んだことを研究に役立てていきたい。

参考文献

この記事は以下の情報を参考にして執筆しました。
https://pystyle.info/matplotlib-create-subplots/
https://www.yutaka-note.com/entry/matplotlib_figure
https://www.python.ambitious-engineer.com/archives/2680

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?