Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 744
Arximede Avatar asked Jul 28 '18 04:07

Arximede


1 Answers

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()
like image 164
ImportanceOfBeingErnest Avatar answered Sep 28 '22 17:09

ImportanceOfBeingErnest