LoginSignup
2
1

More than 5 years have passed since last update.

特にリモートでMatplotlibでグラフを描いて保存する際のトラブル予防策

Posted at

リモート環境でmatplotlib.pyplot.plotを実行

DISPLAY変数がないリモート環境でmatplotlib.pyplot.plotを実行しようとすると

RuntimeError: Invalid DISPLAY variable

のような例外が出てしまいます。次の2パターンのいずれかで対策できます。

import matplotlib
import os

if "DISPLAY" is not in os.environ:
  matplotlib.use("Agg")

from matplotlib import pyplot

以上の方法がよく採用されますが、isortなどパッケージのソート順をいじるツールなどと相性が悪いです。次のように書けば、追加の記載なしでisortなどが問題なく使えます。ただし、程度の多少はわかりませんが、オーバーヘッドはあります。

from matplotlib import pyplot
import os

if "DISPLAY" is not in os.environ:
  pyplot.switch_backend("Agg")

図を複数保存

図を複数保存する際にもトラップがあります。次のpyplot.close()を書かないと2つ目以降のグラフが以前plotしたグラフの上に書かれてしまいます。savefigshowと違ってキャンバスを消してくれません。+忘れないようにしましょう。

windows = (scipy.signal.hamming, scipy.signal.hann, scipy.signal.blackman)
for window in windows():
  pyplot.plot(window(256))
  pyplot.savefig(window.__name__ + ".svgz")
  pyplot.close()
2
1
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
2
1