如何在matplotlib中的轮廓图上绘制矢量场? [英] How to plot a vector field over a contour plot in matplotlib?

查看:87
本文介绍了如何在matplotlib中的轮廓图上绘制矢量场?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设法绘制了一个向量场和一个等高线图,并希望将它们显示在彼此的顶部,我环顾四周,但不太了解图形和子图是如何工作的.这是我的代码:

I've managed to plot a vector field and a contour plot and would like to display both of them on top of each other, I've looked around but don't quite understand how figure and subplots work. Here is my code:

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(),等高线图也会覆盖箭袋.
  • Calling plt.show() in between the plots: this makes them separate figures, instead of overlaying one on the other
  • Plotting the quiver plot before the contour plot: so even if you removed the show(), the contour plot would cover up the quiver.

简单修复!

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

结果:

这篇关于如何在matplotlib中的轮廓图上绘制矢量场?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆