Bus errorとSegmentation faultに困ったら見るブログ

物理の研究者による日々の研究生活のメモ書きです ( python/emacs/html/Japascript/シェルスクリプト/TeX/Mac/C言語/Linux/git/tmux/R/ポケモンGO)

【matplotlib, jupyter lab】プロットした画像を画面に表示せずに保存だけしたいとき

img = cv2.imread(fname, cv2.IMREAD_UNCHANGED)
height, width = img.shape

hist_data = img.flatten()

 

fig = plt.figure(figsize = (20, 10))

 

ax1 = fig.add_subplot(1, 2, 1)     
ax1.imshow(img, 'gray')
ax1.set_xticks()
ax1.set_yticks(
) # to hide tick values on X and Y axis        

 

ax2 = fig.add_subplot(1, 2, 2) 
ax2.hist(hist_data, bins=50)
ax2.set_xlim(0, 500)
ax2.set_title("%s" % fname)
ax2.set_xlabel("Count")
ax2.set_ylabel("Histogram")
ax2.set_yscale('log')    

 

plt.savefig("hist_%s" % fname)
plt.close()  

のように保存した後で、plt.close()すると、画面にプロットが表示されない

matplotlibでグラフを表示しないで画像として保存する #Python - Qiita

 

他にもそもそもjupyter labの設定として、ノートブック上に画像を表示しない方法もある

画像を保存するときにjupyter notebook上にプロットを表示したくないとき (%はタイポではなくてこのまま打つ)

from matplotlib import pyplot as plt
%matplotlib agg

 

jupyter notebook上にプロットを表示したいとき
(これを書かないとx11が立ち上がってそこでプロットを見せてくる)

from matplotlib import pyplot as plt
%matplotlib inline