I'm using a mac and when I do the following with matplotlib:
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import pylab as P
...
plt.plot(x,y)
plt.show() <-- nothing happens
plt.savefig('figure.png') <-- works fine
So, plt.show
does not open a window or anything while plt.savefig
works fine.
What could be the problem?
show() and plt. draw() are unnecessary and / or blocking in one way or the other.
Using plt. show() in Matplotlib mode is not required.
It just means that any graph which we are creating as a part of our code will appear in the same notebook and not in separate window which would happen if we have not used this magic statement.
Occasionally, problems with Matplotlib can be solved with a clean installation of the package. In order to fully remove an installed Matplotlib: Delete the caches from your Matplotlib configuration directory. Delete any Matplotlib directories or eggs from your installation directory.
For me I had some code like this:
from matplotlib import pyplot as plt
figure = plt.Figure()
axes = figure.add_subplot()
axes.plot([1,2], [1,2])
plt.show()
plt.show() didn't block or do anything. If I changed the code to this, then it worked:
figure = plt.Figure()
plt.plot([1,2], [1,2])
plt.show()
My issue was that I had multiple plots to show in one subplot, so I needed the axes. This was the fix:
figure, axes = plt.subplots()
axes.plot([1,2], [1,2])
plt.show()
Pyplot will only pop up a figure window if
matplotlib.rcParams['interactive'] == True
This is the case if you:
plt.ion()
in your script, ormatplotlib.interactive(True)
, or--pylab
option at the command line.When interactive mode is off, you generally have to call plt.show()
explicitly to make the figure window pop up. This is because we often want to call plot multiple times to draw various things before displaying the figure (which is a blocking call).
Edit (after the question was modified):
One reason for plt.show()
not popping up a figure window is that you haven't activated an interactive backend. Check the output of plt.get_backend()
- if it returns 'agg'
, for example, you have a non-interactive backend.
If this is your problem, you may add lines like
import matplotlib
matplotlib.use('MacOSX')
At the start of your script to specify the backend. This needs to be placed before any other matplotlib related imports.
To make such a change permanent, you can specify a different backend as default by modifying your matplotlib rcfile. The location of this file is found by calling matplotlib.matplotlib_fname()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With