python - 如何用 Python 插值向量场?
问题描述
我有一个 2D 向量场(实际上它是 3D,但如果我们知道如何用 2D 来做,我认为它很容易推广到 3D),如下所示:
import matplotlib.pyplot as plt, numpy as np
x = [0, 0, 1, 1, 2, 2, 0, 1, 2]
y = [1, 2, 1, 2, 1, 2, 1.5, 1.5, 1.5]
u = [0.5, -1, 0, 0, 0.25, 1, 0, 0, 0.75]
v = [1, 1, 1, 1, 1, 1, 1, 1, 1]
plt.quiver(x, y, u, v)
plt.show()
如何平滑地插值这个向量场?
我知道如何使用np.polyfit
,但我不知道如何对矢量场进行插值。
示例:我想插入[0,2]x[1,2]
数百个箭头。
解决方案
使用 NumPymeshgrid
和 SciPy 的interpolate.griddata
方法,这可能是一个快速可行的解决方案:
import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate
x = [0, 0, 1, 1, 2, 2, 0, 1, 2]
y = [1, 2, 1, 2, 1, 2, 1.5, 1.5, 1.5]
u = [0.5, -1, 0, 0, 0.25, 1, 0, 0, 0.75]
v = [1, 1, 1, 1, 1, 1, 1, 1, 1]
plt.figure(1)
plt.quiver(x, y, u, v)
xx = np.linspace(0, 2, 10)
yy = np.linspace(1, 2, 10)
xx, yy = np.meshgrid(xx, yy)
points = np.transpose(np.vstack((x, y)))
u_interp = interpolate.griddata(points, u, (xx, yy), method='cubic')
v_interp = interpolate.griddata(points, v, (xx, yy), method='cubic')
plt.figure(2)
plt.quiver(xx, yy, u_interp, v_interp)
plt.show()
插值图的输出:
玩弄要在np.linspace
调用中创建的点数,会给您或多或少的箭头。
希望有帮助!
推荐阅读
- sql - 我有一个查询以时间间隔选择某些数据的总和,我如何也获得这些时间间隔的总数?
- c++ - 如何释放函数中分配的内存而不返回其指针?
- api - EF Core 根据 API 中的参数调用数据库
- c++ - 为什么此代码段会出现分段错误?
- java - Flutter:如何对堆栈跟踪进行去混淆处理?
- javascript - 调用 new Audio() 的更好方法;
- ruby-on-rails - webpack:TypeError:validateOptions 不是函数
- r - 线图形状
- android - 从另一个线程访问 UI 线程的视图
- r - 使用 sjPlot 更改 plot_model 中的变量标签以获得随机效应