一个等高线图上的函数总和

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

有等高线图,我想要三个函数的图形总和。这些是相同的函数,但仅在坐标上有所不同,并且每个函数都可以正常工作,但是当我尝试获取这些函数的总和时,绘图切割点对于所有该图来说并不常见。可能是面膜功能有问题?

import numpy as np
import matplotlib.pyplot as plt

xx = np.linspace(-200, 200, 200)
yy = np.linspace(-200, 200, 200)
X, Y = np.meshgrid(xx, yy)        

r1 = np.sqrt(np.square(X) + np.square(Y))
r2 = np.sqrt(np.square(20 - X) + np.square(20 - Y))
r3 = np.sqrt(np.square(-40 - X) + np.square(40 - Y))

# Function with coordinates 1
Z1 = 3 * (r1/100)**4 - 8 * (r1/100)**3 + 6 * (r1/100)**2
Z1 = np.ma.array(Z1, mask=r1>=100)

# Function with coordinates 2
Z11 = 3 * (r2/100)**4 - 8 * (r2/100)**3 + 6 * (r2/100)**2
Z11 = np.ma.array(Z11, mask=r2>=100)

# Function with coordinates 3
Z21 = 3 * (r3/100)**4 - 8 * (r3/100)**3 + 6 * (r3/100)**2
Z21 = np.ma.array(Z21, mask=r3>=100)

#Sum of functions
Z01 = Z1 + Z11 + Z21

cs = plt.contour(X, Y, Z01, 20, cmap=plt.cm.YlGn_r, levels = 10, extend='max')
cs2 = plt.contourf(X, Y, Z01, 20,cmap=plt.cm.YlOrBr, levels = 10, extend='max')

plt.clabel(cs2)
plt.clabel(cs, fontsize=10, colors=plt.cm.Reds(cs.norm(cs.levels)))
plt.colorbar(cs2)
plt.grid(which='major')
plt.title('Contours Plot')
plt.xlabel('X (m)')
plt.ylabel('Y (m)')
plt.xlim([0, 200])
plt.ylim([0, 200])
plt.axis('scaled')

plt.tight_layout()
plt.show()

此示例图只有一个函数 (#1) enter image description here

这个带有函数求和的例子(我希望它相互叠加并求和结果)

enter image description here

python numpy matplotlib contour
1个回答
0
投票

问题不在于功能没有共同点。问题在于没有一个函数具有未被屏蔽的值。您可以打印屏蔽数组并看到,例如,所有三个函数的开头和结尾的所有值都被屏蔽了。

对三个函数求和时,您可以将值设置为 0,而不是屏蔽它们。这确保了可以绘制的每个点始终有一个定义的值。

# Function with coordinates 1
Z1 = 3 * (r1/100)**4 - 8 * (r1/100)**3 + 6 * (r1/100)**2
Z1[r1 >= 100] = 0
 
# Function with coordinates 2
Z11 = 3 * (r2/100)**4 - 8 * (r2/100)**3 + 6 * (r2/100)**2
Z11[r2 >= 100] = 0

# Function with coordinates 3
Z21 = 3 * (r3/100)**4 - 8 * (r3/100)**3 + 6 * (r3/100)**2
Z21[r3 >= 100] = 0
© www.soinside.com 2019 - 2024. All rights reserved.