使用弯曲(路径跟踪)向量在python中进行流动可视化

Kie*_*unt 15 python data-visualization matplotlib vector-graphics

我想在python中绘制带有弯曲箭头的矢量场,可以在vfplot(见下文)或IDL中完成.

Boussinesq流动与弯曲的向量

您可以在matplotlib中接近,但使用quiver()限制直线向量(见左下图),streamplot()但似乎不允许对箭头长度或箭头位置(见右下方)进行有意义的控制,即使在更改integration_directiondensity,和maxlength.

示例matplotlib箭头和流图

那么,有没有可以做到这一点的python库?或者有没有办法让matplotlib做到这一点?

Dav*_*eth 7

如果您查看 matplotlib 中包含的streamplot.py,第 196 - 202 行(ish,我不知道这是否在版本之间发生了变化 - 我使用的是 matplotlib 2.1.2),我们会看到以下内容:

 ... (to line 195)
    # Add arrows half way along each trajectory.
    s = np.cumsum(np.sqrt(np.diff(tx) ** 2 + np.diff(ty) ** 2))
    n = np.searchsorted(s, s[-1] / 2.)
    arrow_tail = (tx[n], ty[n])
    arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2]))
 ... (after line 196)
Run Code Online (Sandbox Code Playgroud)

将该部分更改为此将达到目的(更改 n 的分配):

 ... (to line 195)
    # Add arrows half way along each trajectory.
    s = np.cumsum(np.sqrt(np.diff(tx) ** 2 + np.diff(ty) ** 2))
    n = np.searchsorted(s, s[-1]) ### THIS IS THE EDITED LINE! ###
    arrow_tail = (tx[n], ty[n])
    arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2]))
 ... (after line 196)
Run Code Online (Sandbox Code Playgroud)

如果您修改此设置以将箭头放在末尾,那么您可以生成更符合您喜好的箭头。

此外,从函数顶部的文档中,我们看到以下内容:

*linewidth* : numeric or 2d array
        vary linewidth when given a 2d array with the same shape as velocities.
Run Code Online (Sandbox Code Playgroud)

线宽可以是numpy.ndarray,如果您可以预先计算所需的箭头宽度,则可以在绘制箭头时修改铅笔宽度。看来这部分已经为您完成了。

因此,结合缩短箭头最大长度、增加密度、添加 start_points,以及调整函数以将箭头放在末尾而不是中间,您可以获得所需的图形。

通过这些修改和以下代码,我能够得到更接近您想要的结果:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.patches as pat

w = 3
Y, X = np.mgrid[-w:w:100j, -w:w:100j]
U = -1 - X**2 + Y
V = 1 + X - Y**2
speed = np.sqrt(U*U + V*V)

fig = plt.figure(figsize=(14, 18))
gs = gridspec.GridSpec(nrows=3, ncols=2, height_ratios=[1, 1, 2])

grains = 10
tmp = tuple([x]*grains for x in np.linspace(-2, 2, grains))
xs = []
for x in tmp:
    xs += x
ys = tuple(np.linspace(-2, 2, grains))*grains


seed_points = np.array([list(xs), list(ys)])
# Varying color along a streamline
ax1 = fig.add_subplot(gs[0, 1])

strm = ax1.streamplot(X, Y, U, V, color=U, linewidth=np.array(5*np.random.random_sample((100, 100))**2 + 1), cmap='winter', density=10,
                      minlength=0.001, maxlength = 0.07, arrowstyle='fancy',
                      integration_direction='forward', start_points = seed_points.T)
fig.colorbar(strm.lines)
ax1.set_title('Varying Color')

plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

matplotlib 图表示例

tl;dr:去复制源代码,并将其更改为将箭头放在每个路径的末尾,而不是中间。然后使用您的流图而不是 matplotlib 流图。

编辑:我的线宽有所不同


Kie*_*unt 6

David Culbreth 的修改开始,我重写了函数的大部分内容streamplot以实现所需的行为。数量有点太多,无法在此处全部指定,但它包括长度归一化方法并禁用轨迹重叠检查。我附加了新curved quiver函数与原始函数streamplot和的两个比较quiver

在此输入图像描述 在此输入图像描述

  • 这是太棒了!您愿意提交您的“curved quivers”代码以添加到 matplotlib 代码库中吗?这看起来应该是一个核心绘图功能。这是他们的 [contrib 页面](https://matplotlib.org/devel/contributing.html) 的链接 (2认同)

Art*_*lle 6

这是一种在普通 pyplot 中获得所需输出的方法(即,无需修改streamplot函数或任何花哨的东西)。提醒一下,我们的目标是可视化带有弯曲箭头的矢量场,其长度与矢量的范数成正比。

诀窍是:

  1. 制作没有从给定点向后追踪的箭头的流图(请参阅)
  2. 从该点开始绘制一个箭袋。使箭袋足够小,以便只有箭头可见
  3. 对每个种子重复 1. 和 2. ,并将流图的长度缩放为与向量的范数成比例。
import matplotlib.pyplot as plt
import numpy as np
w = 3
Y, X = np.mgrid[-w:w:8j, -w:w:8j]

U = -Y
V = X
norm = np.sqrt(U**2 + V**2)
norm_flat = norm.flatten()

start_points = np.array([X.flatten(),Y.flatten()]).T

plt.clf()
scale = .2/np.max(norm)

plt.subplot(121)
plt.title('scaling only the length')
for i in range(start_points.shape[0]):
    plt.streamplot(X,Y,U,V, color='k', start_points=np.array([start_points[i,:]]),minlength=.95*norm_flat[i]*scale, maxlength=1.0*norm_flat[i]*scale,
                integration_direction='backward', density=10, arrowsize=0.0)
plt.quiver(X,Y,U/norm, V/norm,scale=30)
plt.axis('square')



plt.subplot(122)
plt.title('scaling length, arrowhead and linewidth')
for i in range(start_points.shape[0]):
    plt.streamplot(X,Y,U,V, color='k', start_points=np.array([start_points[i,:]]),minlength=.95*norm_flat[i]*scale, maxlength=1.0*norm_flat[i]*scale,
                integration_direction='backward', density=10, arrowsize=0.0, linewidth=.5*norm_flat[i])
plt.quiver(X,Y,U/np.max(norm), V/np.max(norm),scale=30)

plt.axis('square')
Run Code Online (Sandbox Code Playgroud)

结果如下:

弯曲箭袋