我已经设法绘制了一个向量场和一个等高线图,并希望将它们显示在彼此之上,我环顾四周,但不太了解图形和子图是如何工作的。这是我的代码:
from matplotlib.pyplot import cm
import numpy as np
import matplotlib.pyplot as plt
# Vector Field
Y, X = np.mgrid[-2:2:20j, -2:2:20j]
U =(1 - 2*(X**2))*np.exp(-((X**2)+(Y**2)))
V = -2*X*Y*np.exp(-((X**2)+(Y**2)))
speed = np.sqrt(U**2 + V**2)
UN = U/speed
VN = V/speed
plt.quiver(X, Y, UN, VN,
color='Teal',
headlength=7)
plt.show()
# Countour Plot
X, Y = np.mgrid[-2:2:100j, -2:2:100j]
Z = X*np.exp(-(X**2 + Y**2))
cp = plt.contourf(X, Y, Z)
plt.colorbar(cp)
plt.show()
最佳答案
你有两个问题:
plt.show()
:这使它们成为单独的图形,而不是将一个图形叠加在另一个 show()
,等高线图也会掩盖箭袋。 简单修复!
from matplotlib.pyplot import cm
import numpy as np
import matplotlib.pyplot as plt
# Contour Plot
X, Y = np.mgrid[-2:2:100j, -2:2:100j]
Z = X*np.exp(-(X**2 + Y**2))
cp = plt.contourf(X, Y, Z)
cb = plt.colorbar(cp)
# Vector Field
Y, X = np.mgrid[-2:2:20j, -2:2:20j]
U =(1 - 2*(X**2))*np.exp(-((X**2)+(Y**2)))
V = -2*X*Y*np.exp(-((X**2)+(Y**2)))
speed = np.sqrt(U**2 + V**2)
UN = U/speed
VN = V/speed
quiv = plt.quiver(X, Y, UN, VN, # assign to var
color='Teal',
headlength=7)
plt.show()
结果:
关于python - 如何在matplotlib中的等高线图上绘制矢量场?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40939821/