17
8

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

matplotlibでグラフを大量生成する際、画面にはグラフを表示させたくない( jupyter環境)

Posted at

結論としては plt.close() で解決です。

はじめに

jupyter(Google Colab.)環境で、matplotlibを利用して、大量のグラフを生成して画像ファイルとして保存したい場合、ノートブックの実行結果セル(画面上)にはグラフを表示させたくない場合があります。

特に、20枚を超えるグラフを表示させようとすると、次のような警告もでてきます。

/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:8:
RuntimeWarning: More than 20 figures have been opened.
Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory.
(To control this warning, see the rcParam figure.max_open_warning).

この問題の回避についてのメモです。

現状

次のコードは「平均50、標準偏差10に従う40個の正規乱数を生成して、そのヒストグラムを描いてpngファイルとして保存するもの」です。

50セットを試行したときの各セットの分布をみるために、50回のループをまわしています。

実行結果セルに大量のグラフが出力されてしまう
import numpy as np
import matplotlib.pyplot as plt

# 50枚の画像ファイルを生成
for i in range(50) : 
  dat = (np.random.normal(50,10,size=40)).astype(np.int64)
  plt.figure()
  plt.hist(dat,bins=10,range=(0,100))
  plt.yticks(range(0,31,10))
  plt.xlim(0,100)
  plt.ylim(0,30)
  plt.savefig(f'fig{i}.png') # 画像ファイルとして保存

上記コードを実行すると冒頭の警告が表示され、また実行結果セルに大量のグラフが並んでノートブックが見づらくなってしまいます。同時に、ノートブック(xxxx.ipynb)には実行結果の画像も内包されるので、そのファイルサイズも大きくなってしまいます。

※ ノートブック環境では、plt.show() を明示しなくてもグラフが自動で画面出力されます。

解決

グラフをファイル出力 plt.savefig(...) した後に、plt.close() を入れることで解決されます。

実行結果セルにグラフを出力しない
import numpy as np
import matplotlib.pyplot as plt

for i in range(50) : 
  dat = (np.random.normal(50,10,size=40)).astype(np.int64)
  plt.figure()
  plt.hist(dat,bins=10,range=(0,100))
  plt.yticks(range(0,31,10))
  plt.xlim(0,100)
  plt.ylim(0,30)
  plt.savefig(f'fig{i}.png')
  plt.close() # ■■■ 追加 ■■■

上記コードを実行すると、実行結果セルには何も出力されません。無論、ファイル出力は問題なく行なわれます。

17
8
0

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
17
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?