よく使う設定と画像保存

グラフを描く時によく使う設定

import matplotlib.pyplot as plt

rcParams_dict = {
    # ---------- figure
    'figure.figsize': [8, 6],
    'figure.dpi': 120,
    'figure.facecolor': 'white',
    # ---------- axes
    'axes.grid': True,
    'axes.linewidth': 1.5,
    # ---------- ticks
    'xtick.direction': 'in',
    'ytick.direction': 'in',
    'xtick.major.width': 1.0,
    'ytick.major.width': 1.0,
    'xtick.major.size': 8.0,
    'ytick.major.size': 8.0,
    # ---------- lines
    'lines.linewidth': 2.5,
    'lines.markersize': 12,
    # ---------- grid
    'grid.linestyle': ':',
    # ---------- font
    'font.family': 'Times New Roman',
    'mathtext.fontset': 'cm',
    #'mathtext.fontset': 'stix',
    'font.size': 20,
    'axes.labelsize': 26,
    'legend.fontsize': 26,
    'svg.fonttype': 'path',  # Embed characters as paths
    #'svg.fonttype': 'none',  # Assume fonts are installed on the machine
    'pdf.fonttype': 42,  # embed fonts in PDF using type42 (True type)
}

plt.rcParams.update(rcParams_dict)

プロット例

ここでは,plt.plot()のような書き方ではなく fig, ax = plt.subplots(1, 1)のようなオブジェクト指向インターフェースを使用.こちらの書き方に慣れた方が細かい設定ができて便利.

fig, ax = plt.subplots(1, 1)
ax.plot([1, 2 ,3, 4], label='$y = x$')
ax.set_xlabel('test $x$')
ax.set_ylabel('test $y$')
ax.legend(loc='best', frameon=True)

jupyterlabやVScodeではグラフを作成した後にfig(名前は自分で決める)と打ち込んで実行すれば グラフがいつでも再表示される.

保存

bbox_inches='tight'をつけると,無駄な余白を省いてくれる. 最初の設定でplt.rcParams['figure.facecolor'] = 'white' としているので背景は白. これがない場合はグラフ領域外(軸とか軸ラベルの部分)は無色透明になる.

# ---------- save figure
fig.savefig('fig.png', bbox_inches='tight')    # PNG
#fig.savefig('fig.png', bbox_inches='tight', dpi=300)    # high dpi PNG
#fig.savefig('fig.svg', bbox_inches='tight')    # SVG
#fig.savefig('fig.pdf', bbox_inches='tight')    # PDF
次へ