12
5

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 3 years have passed since last update.

【Python】複数グラフを描くときはravel()が便利

Posted at

複数のグラフを描画する際、ravel()を使うと制御が楽。

plt.subplots()するとaxesに二次元配列ができるため、for loopでグラフを描くときネストしなければならないが、ravel()で一次元配列にしてやれば、ネスト不要。

import pandas_datareader.data as web
import datetime
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

dic = {'Unemployment rate':'UNRATE',
       'USHY spread': 'BAMLH0A0HYM2',
       'CPI':'CPIAUCSL',
       '10 year treasury': 'DGS10',
      'Federal Funds Rate': 'FEDFUNDS',
      'Industrial Production Index':'INDPRO',
      'Household Debt to GDP': 'HDTGPDUSQ163N',
      'Real GDP': 'A191RL1Q225SBEA',
      'WTI oil price': 'WTISPLC',
      'VIX': 'VIXCLS',
      'S&P500': 'SP500'}

source = 'fred'

start = datetime.datetime(2015, 1, 1)
end = datetime.datetime(2020, 5, 1)

h = ((len(dic)+1)//2)*4

fig, axes = plt.subplots(6,2, figsize = (15,h))

for ax, (ttl, symbol) in zip(axes.ravel(),dic.items()):
    dt = web.DataReader(symbol,source, start, end)
    ax.plot(dt)
    ax.set_title(ttl) 
    ax.grid(True)

plt.tight_layout()
plt.savefig('FRED',bbox_inches="tight")   

FRED.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?