简体   繁体   中英

How do plt.plot(x,y) and plt.show() work the way they do?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM