在matplotlib pylab中添加现有的绘图

问题描述 投票:0回答:1

我正在为一系列情节创建轮廓。我将轮廓对象存储在列表中,然后我创建一个新的图。如何重新使用新图中存储的图?

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)

这两个数字是针对A:The first contourf plot created in the loop的不同值生成的

The second contourf plot created in the loop

现在继续尝试重新使用存储的QuadContourSet对象:

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()

创建新绘图的常规方法不起作用,因为我只想重用之前存储的那些。

python matplotlib
1个回答
1
投票

解决方案非常简单;将存储的QuadContourSet对象再次传递给plt.contour:

plt.contour(c0, colors=color)
plt.contour(c1, colors=color, linestyles='dashed')

所以完整的工作代码现在看起来像:

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()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.