よく使う設定と画像保存

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

import matplotlib.pyplot as plt

# ---------- figure
plt.rcParams['figure.figsize'] =[8, 6]
plt.rcParams["figure.dpi"] = 120
plt.rcParams['figure.facecolor'] = 'white'

# ---------- axes
plt.rcParams['axes.grid'] = True
plt.rcParams['axes.linewidth'] = 1.5

# ---------- ticks
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
plt.rcParams['xtick.major.width'] = 1.0
plt.rcParams['ytick.major.width'] = 1.0
plt.rcParams['xtick.major.size'] = 8.0
plt.rcParams['ytick.major.size'] = 8.0

# ---------- lines
plt.rcParams['lines.linewidth'] = 2.5
plt.rcParams['lines.markersize'] = 12

# ---------- grid
plt.rcParams['grid.linestyle'] = ':'

# ---------- font
plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['mathtext.fontset'] = 'cm'
#plt.rcParams['mathtext.fontset'] = 'stix'
plt.rcParams['font.size'] = 20
plt.rcParams['axes.labelsize'] = 26
plt.rcParams['legend.fontsize'] = 26
plt.rcParams['svg.fonttype'] = 'path'    # Embed characters as paths
#plt.rcParams['svg.fonttype'] = 'none'    # Assume fonts are installed on the machine
plt.rcParams['pdf.fonttype'] = 42    # embed fonts in PDF using type42 (True type)

プロット例

ここでは,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
次へ