1

I wanted to know the basic backbone process going on between plt.plot(x,y) and plt.show() commands of matplotlib.pyplot.

To elaborate it a bit, the piece of code:

plt.plot(x , y)
plt.show()

show the desired graph (no problem with that).

Also, the code:

plt.plot(x , y)
plt.plot(p , q)
plt.show()

works fine as well. It shows the two plots created by the lists x & y and p & q.

Now here is something that I found very interesting when coding dynamically in ipython.

In [73]: plt.plot(x , y)
#normal plotting function.
In [78]: plt.show()
#shows a graph as intended.
In [79]: plt.show()
#shows nothing.

Now, no matter how many times I call plt.show() (after I've called it once) it doesn't display the graph at all. Why is so?.

PS: To my understanding maybe there is an object being created and deleted withing this process. But neither I'm sure nor convinced.

Thanks in advance.

Shivam Sharma
  • 901
  • 1
  • 6
  • 12
  • I suspect this is really a duplicate. You can save figures etc to reshow - once `show()` is done its done. https://stackoverflow.com/questions/5524858/matplotlib-show-doesnt-work-twice – doctorlove Sep 27 '17 at 14:44
  • @doctorlove Yes I did stumbled upon the hyperlinked question question before posting my question. I wanted to know how(and if possible why) this happens. I do understand that once `show()` is called it's done. The question is *how it is done*. – Shivam Sharma Sep 27 '17 at 14:55

1 Answers1

3

Pyplot uses or is a so called "statemachine". It stores a number of figures and references to the current axes and figure. Once show is called, all figures are shown and once show returns, they are removed from the statemachine.

On a subsequent call to show there are no figures to show anymore, hence not output is shown.

Therefore there is some (maybe unwritten or implicit) assumption that show is called exactly once in a script.

It may be worth noting that although figures are removed from the statemachine they remain in memory until they are closed. So they may be reused under certain circumstances and depending on the desired workflow.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712