Arximede
Arximede

Reputation: 391

plt.figure.Figure.show() does nothing when not executing interactively

So I have a following simple code saved in a .py file, and executing in shell:

import matplotlib.pyplot as plt

myfig = plt.figure(figsize=(5, 5))
ax1 = myfig.add_subplot(1, 1, 1)
myfig.show()

However it does nothing upon execution, no errors nothing.

Then when I start Ipython in shell, and type exact same code, it does pop up an empty window. Why is that?

of course I can use plt.show() and everything is fine. But lets say I have two figures, fig1 and fig2, and there is stuff in both figs, and I want to only display one of them, how can I do that? plt.show() plots both of them.

Sorry if this is stupid I'm just curious why when working interactively in ipython, window pops up upon calling fig1.show() but nothing happens when I execute same script in shell but doing: python myfile.py

Thank you!

Upvotes: 10

Views: 19148

Answers (3)

Sreekiran A R
Sreekiran A R

Reputation: 3421

you need add an extra line

%matplotlib inline

To get the plot in jupyter notebook. for more you can refer http://ipython.readthedocs.io/en/stable/interactive/tutorial.html#magics-explained

Upvotes: -1

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339280

plt.show starts an event loop, creates interactive windows and shows all current figures in them. If you have more figures than you actually want to show in your current pyplot state, you may close all unneeded figures prior to calling plt.show().

fig1 = plt.figure()
ax1 = fig1.add_subplot(1, 1, 1)
ax1.plot([1,3,4])

fig2 = plt.figure()
ax2 = fig2.add_subplot(1, 1, 1)
ax2.plot([1,2,5])

# close first figure
plt.close(fig1)
# show all active figures (which is now only fig2)
plt.show()

In contrast fig.show() will not start an event loop. It will hence only make sense in case an event loop already has been started, e.g. after plt.show() has been called. In non-interactive mode that may happen upon events in the event loop. To give an example, the following would show fig2 once a key on the keyboard is pressed when fig1 is active.

import matplotlib.pyplot as plt

fig1 = plt.figure()
ax1 = fig1.add_subplot(1, 1, 1)
ax1.plot([1,3,4])

def show_new_figure(evt=None):
    fig2 = plt.figure()
    ax2 = fig2.add_subplot(1, 1, 1)
    ax2.plot([1,2,5])
    fig2.show()

# Upon pressing any key in fig1, show fig2.
fig1.canvas.mpl_connect("key_press_event", show_new_figure)

plt.show()

Upvotes: 8

Reblochon Masque
Reblochon Masque

Reputation: 36682

You need to modify your code like this:

import matplotlib.pyplot as plt

myfig = plt.figure(figsize=(5, 5))
ax1 = myfig.add_subplot(1, 1, 1)
plt.plot((1, 2, 3))       # <- plot something
plt.show()                # <- show the plot

more info in matplotlib docs here.

Upvotes: 0

Related Questions