LoginSignup
4
1

More than 1 year has passed since last update.

plt.subplots()のaxesをfor文1つでイテレーションする

Last updated at Posted at 2022-10-12

概要

fig, axes = plt.subplots(2,3)のaxesの要素にfor文でアクセスするとき,普段なら,

for i in range(2):
    for j in range(3):
        axes[i, j]

とするが,これを

for i in range(6):
    axes[i]

のようにfor文1つでアクセスする方法を考えた.

TL;DR

for文の前にaxes = axes.reshape(-1)を置くだけ

fig, axes = plt.subplots(2, 3)

axes = axes.reshape(-1)

for i in range(6):
    ...

axesは単なる二次元配列なので,1次元にしてやればよい.

ランダムな周波数で10個のサイングラフを生成する.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#サンプルデータ生成
data_size = 10
f = np.random.randint(1, 10, data_size)
t = np.arange(0, 10, 0.01)
data = [np.sin(2*np.pi*i*t) for i in f]

fig, axes = plt.subplots(5, 2)

#ここでaxesの配列を1次元にする
axes = axes.reshape(-1)

fig.tight_layout()

for i, datum in enumerate(data):
    axes[i].plot(data[i])
plt.show()

結果
output.png

4
1
3

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
4
1