1. 結論
fig = plt.figure()
のところがfig = plt.Figure()
と、大文字で打ち間違えているせいかも。
2. 目次
2. 使用環境
- python 3.7 (conda 4.9.2)
- Matplotlib 3.3.4
3. 実例
以下は普通に動くはず。※本ページのスクリプトの利用は自己責任でお願いします。
>>> import matplotlib.pyplot as plt
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111, facecolor="white")
>>> ax.plot(a,b)
[<matplotlib.lines.Line2D object at 0x7fb5b8888390>]
>>> plt.show() # ウィンドーが出てくる
>>> fig.savefig("a.png")
ここでfig
の型を確認しておくと、
>>> type(fig)
<class 'matplotlib.figure.Figure'>
である。上のプログラムのplt.figure()
をplt.Figure()
に置き換えると、
>>> import matplotlib.pyplot as plt
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> fig = plt.Figure()
>>> ax = fig.add_subplot(111, facecolor="white")
>>> ax.plot(a,b)
[<matplotlib.lines.Line2D object at 0x7facccd9ed50>]
>>> plt.show() # ウィンドーが出てこない!!
>>> fig.savefig("b.png")
こうなる.特にエラーは出ないが、plt.show()
で出てくるべきウィンドーが出ない。ディレクトリを見ると画像はちゃんと保存されていた。型を調べると、
>>> type(fig)
<class 'matplotlib.figure.Figure'>
先程と同じもの。では何が違うのかというと、attributeが違う。とくに後者ではshow()
がない。
>>> fig = plt.figure()
>>> fig.show() # ウィンドーが出てくる
>>> fig = plt.Figure()
>>> fig.show()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/python3.7/site-packages/matplotlib/figure.py", line 408, in show
"Figure.show works only for figures managed by pyplot, "
AttributeError: Figure.show works only for figures managed by pyplot, normally created by pyplot.figure()
matplotlib.pyplot.figure()
によって作られたFigure
でないとFigure.show()
は動きませんよ、と言ってくる。けしからん。
4. おわりに
conda で作成したpython 3.8の仮想環境でも同様であった。