shl7
shl7

Reputation: 63

I cannot call show() after close() with matplotlib in python

I'm new to Python (I used MATLAB before), and I find that I cannot call show() after close some figures by close(). My goal is closing figures freely and then show the rest plots at last. Could anyone help me? Thank you.

My system: Python 3.6 on Windows 10. The matplotlib version is 2.2.2. I run my code through Eclipse.

Here is the code:

# Original code
import matplotlib.pyplot as plt

figA = plt.figure('aa')
figB = plt.figure('bb')
plt.close('aa')

plt.plot([2,3],[1,1],color='green')
plt.show()

When I run it, I get the following error in the Eclipse console.

Traceback (most recent call last):

File "D:\a project for testing dionysus\test_pythonPractice.py", line 26, in plt.show()

File "C:\Users\hanlin\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\pyplot.py", line 253, in show return _show(*args, **kw)

File "C:\Users\hanlin\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\backend_bases.py", line 208, in show cls.mainloop()

File "C:\Users\hanlin\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\backends_backend_tk.py", line 1073, in mainloop Tk.mainloop()

File "C:\Users\hanlin\AppData\Local\Programs\Python\Python36\lib\tkinter__init__.py", line 557, in mainloop _default_root.tk.mainloop(n)

AttributeError: 'NoneType' object has no attribute 'tk'

However, if I change the code to either of the following two versions, there is no error.

# Revised ver.1
import matplotlib.pyplot as plt

figA = plt.figure('aa')
figB = plt.figure('bb')
plt.close('bb')

plt.plot([2,3],[1,1],color='green')
plt.show()

or

# Revised ver.2
import matplotlib.pyplot as plt

figA = plt.figure('aa')
figB = plt.figure('bb')
plt.close('aa')

plt.plot([2,3],[1,1],color='green')
plt.show(block=False)
plt.pause(3)

From revised ver.1, my guess is that close() only works on the last added figure. If we remove the previous figure, there will be an "empty" element in the list recording those figures. But this assumption violates the revised ver.2... Does anyone know why and how to solve this problem? Thank you.

Upvotes: 3

Views: 280

Answers (1)

shl7
shl7

Reputation: 63

Thanks to @Mr.T and @DavidG, I figure it out. Now the code becomes

# Revised original code
import matplotlib
matplotlib.use("Qt5Agg")
import matplotlib.pyplot as plt

figA = plt.figure('aa')
figB = plt.figure('bb')
plt.close('aa')

plt.plot([2,3],[1,1],color='green')
plt.show()

The culprit is the backend (default: "TkAgg"), and I set it as "Qt5Agg" now. I install the package pyqt5 by

pip install pyqt5==5.10.1

Note that the pyqt5 version needs to be 5.10.1. The latest one (5.11.2) would cause another error. For details, please read the webpage.

Upvotes: 3

Related Questions