首页 > 解决方案 > 如何使用定义的数学函数在 matplotlib.quiver() 中创建 U、V 参数

问题描述

我有一个非常基本的模型来控制坠落的物体:

# ODE modelling velocity of a falling object
def field(t, v):
    v_dot = 9.8 - (gamma / mass) * v
    return v_dot

我已经针对几个不同的初始条件求解并绘制了这个 ODE。我想使用 matplotlib.quiver() 用斜率场覆盖绘图。

我特别难以整理出 U 和 V 参数。我知道它们是每个箭头应该指向的 x 和 y 方向。

这是我尝试过的,我从另一个答案中收集到的策略:

x = np.linspace(0, 50, 6)
y = np.linspace(0, 150, 16)
X, Y = np.meshgrid(x, y)
f = 9.8 - (gamma / mass) * Y
U, V = np.gradient(f)
Q = plt.quiver(X, Y, U, V)

但是,这绘制了以下内容:

在此处输入图像描述

这绝对是错误的,更不用说丑陋了。当然,我的主要问题似乎是我不知道如何以正确的方式找到 U 和 V。我浏览了其他几个问题,但大多数人做的事情比我复杂得多,而且我似乎无法缩小他们对我更简单问题的回答。

# ODE modelling velocity of a falling object
def field(t, v):
    v_dot = 9.8 - (gamma / mass) * v
    return v_dot

# gamma is the coefficient for air resistance
gamma = 0.392
mass = 3.2

# declare interval and step size
t_0 = 0.
t_n = 100.
delta = 0.05
time = np.arange(t_0, t_n, delta)

fig, axs = plt.subplots(figsize=(10, 6))
fig.suptitle("A Simple Model: Falling Object")

axs.set_title(r"Solution to $\dot{v} = 9.8 - \frac{\gamma}{m}v$")
axs.set_ylabel('Velocity')
axs.set_xlabel('Time')

for x_0 in np.arange(0., 101., 20):
    # Solve for each initial condition x_0
    x = rk4(delta, time, field, x_0)

    # Plot results
    axs.plot(time, x, label=r"$v_0=$%.3f" % x_0)

标签: pythonmatplotlib

解决方案


我认为评论者没有意识到我需要帮助来解决问题的基本概念性质。我知道我又慢又笨,谢天谢地,这个论坛以外的人对此更了解。所以这里有很多评论,以防像我一样慢的人需要帮助。只需将我的 ODE 替换为您想要建模的任何一个,并使用 x 和 y 轴数组来获得您想要的间距:

# ODE for falling object
def field(t, v):
    v_dot = 9.8 - (gamma / mass) * v
    return v_dot

# gamma is the coefficient for air resistance
gamma = 0.392
mass = 3.2

# x and y axis arrays 
x = np.linspace(0,50, 11) # time from zero to 50 inclusive
y = np.linspace(0,100, 11) # initial velocities from 0 to 100 inclusive

# meshgrid creates two arrays of shape(len(y), len(x))
# by pairing the values of these two arrays, we create a set
# of ordered pairs that give our coordinates for the location
# of the quiver arrows we wish to plot.
X, Y = np.meshgrid(x, y)

# We know slope is v' = f(t, v), so we can use trig to get
# to the x and y components of our quiver arrow vectors
theta = np.arctan(field(X, Y))
U = np.cos(theta)
V = np.sin(theta)

plt.quiver(X, Y, U, V)

plt.grid()
plt.show()

推荐阅读