0
1

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

matplotlibで画像は保存できるけどplt.show()が動かなくなるケアレスミス

Last updated at Posted at 2021-04-04

1. 結論

fig = plt.figure()のところがfig = plt.Figure()と、大文字で打ち間違えているせいかも。

2. 目次

1. 結論
2. 使用環境
3. 実例
4. おわりに

2. 使用環境

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の仮想環境でも同様であった。

0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?