【发布时间】:2021-07-31 05:06:00
【问题描述】:
使用"Finding intersection of two contour plots in Python" 作为指导,我收到以下错误消息(代码如下):
<ipython-input-98-993ccd512742> in <module>
9
10
---> 11 intersection_example = findIntersection(c1,c2)
12
<ipython-input-97-995cbb9fd0d0> in findIntersection(contour1, contour2)
2
3 def findIntersection(contour1,contour2):
----> 4 p1 = contour1.collections[0].get_paths()[0]
5 v1 = p1.vertices
6
IndexError: list index out of range
下面的第一个代码示例给了我一个没有错误的 3D 等高线图:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
fig.set_size_inches(18.5, 10.5) #, forward=True)
ax = plt.axes(projection='3d')
x = np.linspace(0, 21, 20)
y = np.linspace(0, 21, 20)
X, Y = np.meshgrid(x, y)
ax.contour3D(X, Y, ((X - 5) * (Y - 5) - 25), 29, cmap='winter')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');
#fig.add_subplot(ax.contour3D(X, Y, Z2, 70, cmap='winter')) #binary'))
ax.contour3D(X, Y, (X**2 + Y**2 - 400), 29, cmap='autumn')
ax.set_title('Contour3D: Using meshgrid X Y ')
以上产生:
下一个示例是使用contour(而不是contour3D)并导致错误的代码段:
IndexError: 列表索引超出范围
这也是findIntersection使用未定义参数调用时产生的错误。
from shapely import geometry
def findIntersection(contour1,contour2):
p1 = contour1.collections[0].get_paths()[0]
v1 = p1.vertices
p2 = contour2.collections[0].get_paths()[0]
v2 = p2.vertices
poly1 = geometry.LineString(v1)
poly2 = geometry.LineString(v2)
intersection = poly1.intersection(poly2)
return intersection
figtst2 = plt.figure()
figtst2.set_size_inches(18.5, 10.5) #, forward=True)
ax2 = plt.axes(projection='3d')
c1 = ax2.contour(X,Y,((X - 5) * (Y - 5) - 25),1,colors='green', linewidths=3)
c2 = ax2.contour(X,Y,(X**2 + Y**2 - 400),1,colors='orange', linewidths=3)
ax2.set_title('Contour Using meshgrid X Y & looking for intersections')
# Error is generated on the next line
intersection_example = findIntersection(c1,c2)
# where coordinates can be accessed by
intersection_example.x ##get x points
intersection_example.y ##get y points
list(intersection_example.coords) ## get in [x,y] formatting
绘制ax2 产生:
注意:如果我使用线性空间 x 和 y 而不是网格 X 和 Y 我得到:
TypeError: 输入 z 必须是二维数组。
【问题讨论】:
-
附录:Z 是一个列表列表(我在 PyCharm 中检查过) - 每个子列表都是一组 20 个浮点数,所以我认为这会将 Z 限定为二维数组
-
实际上 Z、X 和 Y 是列表列表,作为矩阵,它们将是 20x20 矩阵
标签: python matplotlib coordinates intersection contour