我正在尝试绘制简单速度方程的方向场。我明白当我使用两个变量时我必须做什么。我可以理解我必须创建的向量,但我不明白如何仅对一个变量进行创建。我的程序是:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def modelo2(y, t):
dydt = 32 - 0.16 * y
return dydt
t0 = 0 ; tf = 25 ; h = 0.1
t = np.arange(t0,tf+h,h)
for y0 in np.arange(0, 400, 25):
y = odeint(modelo2,y0,t )
plt.plot(t,y,'b')
x = np.arange(0, 400, 20)
z = np.arange(0, 400, 20)
X, Z = np.meshgrid(x, z)
U = modelo2(X,t)
V = modelo2 (Z, t)
plt.quiver(X, Z, U, V, scale = 70)
plt.quiver(X, Z, U, V, scale = 60)
plt.xlabel('time')
plt.ylabel('y(t)')
plt.axis([0,20,0, 500])
plt.show()
我明白了
当我期待这样的事情时
有人可以解释我做错了什么吗?
答案 0 :(得分:1)
改变这个
U = modelo2(X,t)
V = modelo2 (Z, t)
到这里
U = 1.0
V = modelo2(Z, None)
N = np.sqrt(U**2 + V**2)
U /= N
V /= N
如您所见,您定义了 U
错误。将 U
和 V
都减去 N
对标准化向量的幅度是必要的,否则它们在图中的长度将根据每个点的场强而变化。只需设置 U = np.ones(Z.shape)
并且不要除以 N
以查看我在说什么。
其次,您需要在plt.quiver()
plt.quiver(X, Z, U, V, angles='xy')
来自文档:
<块引用>angles : {'uv', 'xy'} or array-like, optional, default: 'uv'
Method for determining the angle of the arrows.
- 'uv': The arrow axis aspect ratio is 1 so that
if *U* == *V* the orientation of the arrow on the plot is 45 degrees
counter-clockwise from the horizontal axis (positive to the right).
Use this if the arrows symbolize a quantity that is not based on
*X*, *Y* data coordinates.
- 'xy': Arrows point from (x, y) to (x+u, y+v).
Use this for plotting a gradient field, for example.
- Alternatively, arbitrary angles may be specified explicitly as an array
of values in degrees, counter-clockwise from the horizontal axis.
In this case *U*, *V* is only used to determine the length of the
arrows.
Note: inverting a data axis will correspondingly invert the
arrows only with ``angles='xy'``.
总而言之,您的代码应如下所示(对变量名称进行一些次要编辑):
def modelo2(y, t):
dydt = 32 - 0.16 * y
return dydt
t0, tf, h = 0, 25, 0.1
t = np.arange(t0, tf+h, h)
ymin, ymax, ystep = 0, 400, 25
y = np.arange(ymin, ymax+ystep, ystep)
for y0 in y:
line = odeint(modelo2, y0, t)
plt.plot(t, line, 'b')
x = np.linspace(t0, tf, 20)
X, Y = np.meshgrid(x, y)
U = 1
V = modelo2(Y, None)
N = np.sqrt(U**2 + V**2)
U /= N
V /= N
plt.quiver(X, Y, U, V, angles='xy')
plt.xlabel('time')
plt.ylabel('y(t)')
plt.axis([t0, tf, ymin, ymax])
plt.show()
结果