How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?
If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = np.exp(x)
fig1, ax1 = plt.subplots()
ax1.plot(x, y)
ax1.set_title("Axis 1 title")
ax1.set_xlabel("X-label for axis 1")
z = np.sin(x)
fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure
ax2.plot(x, z)
ax3.plot(x, -z)
w = np.cos(x)
ax1.plot(x, w) # can continue plotting on the first axis
It is a little more verbose but it's much clearer and easier to keep track of, especially with several figures each with multiple subplots.
When you call figure
, simply number the plot.
x = arange(5)
y = np.exp(5)
plt.figure(0)
plt.plot(x, y)
z = np.sin(x)
plt.figure(1)
plt.plot(x, z)
w = np.cos(x)
plt.figure(0) # Here's the part I need
plt.plot(x, w)
Edit: Note that you can number the plots however you want (here, starting from 0
) but if you don't provide figure with a number at all when you create a new one, the automatic numbering will start at 1
("Matlab Style" according to the docs).
However, numbering starts at 1
, so:
x = arange(5)
y = np.exp(5)
plt.figure(1)
plt.plot(x, y)
z = np.sin(x)
plt.figure(2)
plt.plot(x, z)
w = np.cos(x)
plt.figure(1) # Here's the part I need, but numbering starts at 1!
plt.plot(x, w)
Also, if you have multiple axes on a figure, such as subplots, use the axes(h)
command where h
is the handle of the desired axes object to focus on that axes.
(don't have comment privileges yet, sorry for new answer!)