【问题标题】:Plotting vector field for first order differential equation绘制一阶微分方程的矢量场
【发布时间】:2021-05-27 01:45:31
【问题描述】:

我正在尝试绘制一个简单速度方程的方向场。我明白当我使用两个变量时我必须做什么。我可以理解我必须创建的向量,但我不明白如何只为一个变量创建它。我的程序是:

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

我明白了

当我期待这样的事情时

谁能解释我做错了什么?

【问题讨论】:

  • 我刚刚发布了!谢谢!

标签: python numpy matplotlib field


【解决方案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 的定义是错误的。将UVN 相除对于标准化向量的大小是必要的,否则它们在图中的长度将根据每个点的场强而变化。只需设置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()

结果

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多