LoginSignup
0
0

More than 5 years have passed since last update.

matplotlibで複数のグラフを描画したい

Posted at

それぞれplotすることもできるが,subplotの描き方について,よく使いそうなものをちょこっと纏める.
jupyter notebookを使っている想定で,縦にグラフを並べたい.
statsmodels.api.graphicsを使って,時系列tsの偏自己相関関数と信頼限界をプロットする場面.

均等割ならadd_subplotが好き

subplotでもできるけど

import matplotlib.pyplot as plt
import numpy as np
import pandas
import statsmodels.api as sm

# ts にはSeries形式でデータがあるものとする.リストやndarrayでも良いけど
N         = len(ts)
pacf      = sm.tsa.pacf(ts, nlags=500)
intervals = pandas.DataFrame( [(2/np.sqrt(N-i), -2/np.sqrt(N-i),) for i in range(len(pacf))]
                            , columns=['plus','minus']
                            )

fig = plt.figure(figsize=(9,16),dpi=200)  # 縦長の領域を指定
ax1 = fig.add_subplot(211)                # 縦に2,横に1のsubplotを並べるうち上(1番目)
ax2 = fig.add_subplot(212)                # 縦に2,横に1のsubplotを並べるうち下(2番目)
sm.graphics.tsa.plot_pacf(ts, lags=len(pacf), ax=ax1)
ax2.plot(pacf, '-o')
intervals.plot(ax=ax2)

plt.show()

上1/3と下2/3にそれぞれplotする場合などは,gridspecで

import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
import pandas
import statsmodels.api as sm

# ts にはSeries形式でデータがあるものとする.リストやndarrayでも良いけど
N         = len(ts)
pacf      = sm.tsa.pacf(ts, nlags=500)
intervals = pandas.DataFrame( [(2/np.sqrt(N-i), -2/np.sqrt(N-i),) for i in range(len(pacf))]
                            , columns=['plus','minus']
                            )

fig = plt.figure(figsize=(9,16),dpi=200)  # 縦長の領域を指定
G   = gridspec.GridSpec(3,1)              # 3行1列のグリッドに切る感じ
ax1 = plt.subplot(G[:1,0])                # ndarrayのスライス形式で上からグリッド1つ分を指定
ax2 = plt.subplot(G[1:,0])                # ndarrayのスライス形式で1以降のグリッドを指定
sm.graphics.tsa.plot_pacf(ts, lags=len(pacf), ax=ax1)
ax2.plot(pacf, '-o')
intervals.plot(ax=ax2)

plt.show()
0
0
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
0
0