Reputation: 3727
I am creating contours for a series of plots. I store the contour objects in a list and then later I create a new plot. How can I re-use the stored plots in the new plot?
import numpy as np
import matplotlib.pylab as plt
# Used for calculating z:
A = [0.9, 1.0]
# Contour values we will use:
values = [0.7, 0.8]
# Create points for data:
x = np.linspace(0.0, np.pi, 1000)
y = np.linspace(0.0, np.pi, 1000)
# Grid the data:
xi, yi = np.meshgrid(x, y)
# Lists for storing contours:
CS0 = []
CS1 = []
for a in A:
# Calculate z for this value of A:
z = a * (np.cos(xi)**2 + np.sin(yi)**2)
print np.max(z)
print np.min(z)
# Plot for this iteration:
plt.figure()
plt.contourf(xi, yi, z, 101)
# Create contours for different values:
solid = plt.contour(xi, yi, z, levels=[values[0]])
dashed = plt.contour(xi, yi, z, levels=[values[1]], linestyles='dashed')
plt.show()
# Store chosen contours or a comparative plot later:
CS0.append(solid)
CS1.append(dashed)
These two figures are generated for the different values of A:
Now continue by attempting to re-use the stored QuadContourSet objects:
colours = ['red', 'orange']
plt.close()
plt.figure()
for c0, c1, color, a in zip(CS0, CS1, colours, A):
print type(c0), type(c1)
# Re-use c0 and c1 in this new plot...???....
plt.? = c0 # ???
plt.? = c1 # ???
plt.show()
The normal way to create a new plot doesn't work because I simply want to reuse the ones I stored earlier.
Upvotes: 1
Views: 334
Reputation: 3727
The solution is quite simple; pass the stored QuadContourSet objects to plt.contour again:
plt.contour(c0, colors=color)
plt.contour(c1, colors=color, linestyles='dashed')
So the full working code now looks like:
import numpy as np
import matplotlib.pylab as plt
# Used for calculating z:
A = [0.9, 1.0]
# Contour values we will use:
values = [0.7, 0.8]
# Create points for data:
x = np.linspace(0.0, np.pi, 1000)
y = np.linspace(0.0, np.pi, 1000)
# Grid the data:
xi, yi = np.meshgrid(x, y)
# Lists for storing contours:
CS0 = []
CS1 = []
for a in A:
# Calculate z for this value of A:
z = a * (np.cos(xi)**2 + np.sin(yi)**2)
print np.max(z)
print np.min(z)
# Plot for this iteration:
plt.figure()
plt.contourf(xi, yi, z, 101)
# Create contours for different values:
solid = plt.contour(xi, yi, z, levels=[values[0]])
dashed = plt.contour(xi, yi, z, levels=[values[1]], linestyles='dashed')
plt.show()
# Store chosen contours or a comparative plot later:
CS0.append(solid)
CS1.append(dashed)
colours = ['red', 'orange']
plt.close()
plt.figure()
for c0, c1, color, a in zip(CS0, CS1, colours, A):
print type(c0), type(c1)
# Re-use c0 and c1 in this new plot
plt.contour(c0, colors=color)
plt.contour(c1, colors=color, linestyles='dashed')
# I found that I had to set the axis limits manually:
plt.xlim(np.min(x), np.max(x))
plt.ylim(np.min(y), np.max(y))
plt.show()
Upvotes: 0