plt.show() does nothing when used for the second time

Question:

I am just starting to learn data science using python on Data Camp and I noticed something while using the functions in matplotlib.pyplot

import matplotlib.pyplot as plt

year = [1500, 1600, 1700, 1800, 1900, 2000]
pop = [458, 580, 682, 1000, 1650, 6,127]

plt.plot(year, pop)

plt.show() # Here a window opens up and shows the figure for the first time

but when I try to show it again it doesn’t..

plt.show() # for the second time.. nothing happens

And I have to retype the line above the show() to be able to show a figure again

Is this the normal thing or a problem?

Note: I am using the REPL

Asked By: Trachyte

||

Answers:

Answer

Yes, this is normal expected behavior for matplotlib figures.


Explanation

When you run plt.plot(...) you create on the one hand the lines instance of the actual plot:

>>> print( plt.plot(year, pop) )
[<matplotlib.lines.Line2D object at 0x000000000D8FDB00>]

…and on the other hand a Figure instance, which is set as the ‘current figure’ and accessible through plt.gcf() (short for “get current figure”):

>>> print( plt.gcf() )
Figure(432x288)

The lines (as well as other plot elements you might add) are all placed in the current figure. When plt.show() is called, the current figure is displayed and then emptied (!), which is why a second call of plt.show() doesn’t plot anything.


Standard Workaround

One way of solving this is to explicitly keep hold of the current Figure instance and then show it directly with fig.show(), like this:

plt.plot(year, pop)
fig = plt.gcf()  # Grabs the current figure

plt.show()  # Shows plot
plt.show()  # Does nothing

fig.show()  # Shows plot again
fig.show()  # Shows plot again...

A more commonly used alternative is to initialize the current figure explicitly in the beginning, prior to any plotting commands.

fig = plt.figure()   # Initializes current figure
plt.plot(year, pop)  # Adds to current figure

plt.show()  # Shows plot
fig.show()  # Shows plot again

This is often combined with the specification of some additional parameters for the figure, for example:

fig = plt.figure(figsize=(8,8))

For Jupyter Notebook Users

The fig.show() approach may not work in the context of Jupyter Notebooks and may instead produce the following warning and not show the plot:

C:redactedpathlibsite-packagesmatplotlibfigure.py:459:
UserWarning: matplotlib is currently using a non-GUI backend, so
cannot show the figure

Fortunately, simply writing fig at the end of a code cell (instead of fig.show()) will push the figure to the cell’s output and display it anyway. If you need to display it multiple times from within the same code cell, you can achieve the same effect using the display function:

fig = plt.figure()   # Initializes current figure
plt.plot(year, pop)  # Adds to current figure

plt.show()  # Shows plot
plt.show()  # Does nothing

from IPython.display import display
display(fig)  # Shows plot again
display(fig)  # Shows plot again...

Making Use of Functions

One reason for wanting to show a figure multiple times is to make a variety of different modifications each time. This can be done using the fig approach discussed above but for more extensive plot definitions it is often easier to simply wrap the base figure in a function and call it repeatedly.

Example:

def my_plot(year, pop):
    plt.plot(year, pop)
    plt.xlabel("year")
    plt.ylabel("population")

my_plot(year, pop)
plt.show()  # Shows plot

my_plot(year, pop)
plt.show()  # Shows plot again

my_plot(year, pop)
plt.title("demographics plot")
plt.show()  # Shows plot again, this time with title
Answered By: WhoIsJack

Using command:

%matplotlib

in ipython3 help me to use separate window with plot

Answered By: Erzi

Start ipython3 and issue the commands:

import matplotlib.pyplot as plt
%matplotlib #plot in separate window
fig, ax = plt.subplots() #Appear empty Tcl window for image
ax.plot([1, 2, 3, 4], [5, 6, 7, 8]) #Appear graph in window

enter image description here

Answered By: Erzi

In some version of matplotlib, fig.show() does not block the window for showing plot multiple times. so, Quick fixes using self.fig.waitforbuttonpress() it waits user to press the button for next plot visualisation.

    self.fig.show()
    plt.pause(0.1)
    self.fig.waitforbuttonpress()
Answered By: prabhuiitdhn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.