物理の駅 Physics station by 現役研究者

テクノロジーは共有されてこそ栄える

Python+matplotlib で 発表等で使える文字が大きめのグラフを簡単に作る方法

普通にグラフを作ると、スライドやポスターで使うには文字が小さく出力される。

デフォルト

コード

import numpy as np
import matplotlib.pyplot as plt

def gaussian_func(arr, constant, mean, sigma):
    return constant * np.exp(- (arr - mean) ** 2 / (2 * sigma ** 2))/(2*np.pi*sigma**2)**0.5

x = np.linspace(-5, 5, 1000)
y =gaussian_func(x, 1.0, 0, 1)
fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(x,y,"k-",label="Total")
ax.set_xlim(-5, 5)
ax.set_ylim(0,None)
plt.legend()
plt.ylabel("Probability")
plt.xlabel("Data (cm)")
plt.savefig("test_org.png")
plt.show()

matplotlibは様々な設定が可能で、詳細な設定は他のブログに任せることにするとして、簡単な方法を紹介する。

plt.rcParamsで figsize を小さめ(例えば(4,3))に設定し、出力時は、DPIを大きく(300くらいが適当)、bbox_inchesを tight にするだけで、見栄えの良いグラフになる。

改善後

コード

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [4,3] # 追加行: figsizeを指定

def gaussian_func(arr, constant, mean, sigma):
    return constant * np.exp(- (arr - mean) ** 2 / (2 * sigma ** 2))/(2*np.pi*sigma**2)**0.5

x = np.linspace(-5, 5, 1000)
y =gaussian_func(x, 1.0, 0, 1)
fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(x,y,"k-",label="Total")
ax.set_xlim(-5, 5)
ax.set_ylim(0,None)
plt.legend()
plt.ylabel("Probability")
plt.xlabel("Data (cm)")
plt.savefig("test.png",dpi=300,bbox_inches="tight") #変更行: dpiとbbox_inchesを指定
plt.show()

グラフの要素をさらに操作したい場合はこの記事へ

phst.hateblo.jp