Cubi73
Cubi73

Reputation: 1951

matplotlib.pyplot.Figure.show freezes instantly

Following strange problem: This code

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 2, 3], [3, 0, 3])
fig.show()

causes the graph window (backend: tkagg) to freeze as soon as it opens, however this code

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [3, 0, 3])
plt.show()

opens the graph window (also tkagg) as expected. I tried debugging, but attaching Visual Studio to python.exe and hitting pause causes VS to crash and python_d.exe always complains cannot import name 'multiarray'. I did a fresh reinstall of python (purging all files, installing python 3.6.3 x86_64, pip install matplotlib) and the behavior continues. What is causing this behavior? Is there a way to fix it?

More information about my system: I'm running Windows 8.1 x86_64 with Python v3.6.3:2c5fed8 x86_64 and matplotlib 2.1.0 (rev-id b392d46466e98cd6a437e16b52b3ed8de23b0b52).

Solution:

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 2, 3], [3, 0, 3])

root = fig.canvas._tkcanvas.winfo_toplevel() # Get tkinter root
fig.show()
root.mainloop() # Enter mainloop

Upvotes: 4

Views: 5489

Answers (1)

Don Kirkby
Don Kirkby

Reputation: 56680

I don't see quite the same behaviour, but I'm testing on Python 3.5, matplotlib 2.1, and Ubuntu 16.04. When I run your first version, I see the plot window open very briefly, and then close itself.

However, if you look at the documentation, it's not too surprising that the behaviour of the two examples is different. You're calling two different show() methods.

In the first version, you're calling Figure.show():

If using a GUI backend with pyplot, display the figure window.

In the second version, you're calling pyplot.show():

Display a figure... In non-interactive mode, display all figures and block until the figures have been closed...

I stepped through the second method, and it's basically equivalent to this:

fig.show()
tkinter.mainloop()

So I'm not sure why it's freezing on you, but it probably wasn't what you wanted in the first place. Create the subplots if you want, but call plt.show() at the end.

Upvotes: 2

Related Questions