Reputation: 317
I have a script that produces a number of different figures and saves the handles to a dictionary. Usually I want to plot all of them but sometimes I am working on a single one, and just want to plot that one.
My understanding is that plt.show()
will show all the plots. It seems logical that if I allocate the figures handles (i.e. do fig1 = plt.figure()
) and then use fig1.show()
that should only show the figure associated with that handle.
Here is a MWE:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
y1 = np.random.rand(100)
y2 = np.random.rand(100)
fig1 = plt.figure()
plt.plot(x, y1, 'o')
fig2 = plt.figure()
plt.plot(x, y2, 'o')
fig1.show()
This seems to work but the figure immediately disappears after it is created. My understanding is that fig1.show()
needs to be in a loop, since the class Figure.show()
method does not invoke a while loop like plt.show()
does.
I realise this is similar to the following question: How can I show figures separately in matplotlib? but the accepted answer doesn't seem to address the original problem (as is pointed out in the comments).
Is placing fig1.show()
in a while loop the correct way? If so, how do you do that?
Upvotes: 0
Views: 2443
Reputation: 339052
You might close all other figures except the one you want to show. Then calling plt.show()
will only show the one figure that hasn't been closed.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
y1 = np.random.rand(100)
y2 = np.random.rand(100)
fig1 = plt.figure()
plt.plot(x, y1, 'o')
fig2 = plt.figure()
plt.plot(x, y2, 'o')
def figshow(figure):
for i in plt.get_fignums():
if figure != plt.figure(i):
plt.close(plt.figure(i))
plt.show()
figshow(fig2)
Upvotes: 2
Reputation: 6863
You could add a statement that waits for user input, then the figure will show, and close after you press a key:
fig1.show()
raw_input()
Upvotes: 2