Skip to main content
 首页 » 编程设计

python之使用 Matplotlib 绘制流线图之Python

2024年11月01日9wayfarer

我正在尝试使用 Matplotlib 绘制一些流线图。

到目前为止我有这段代码,作为绘制 10 x 10 向量场的示例:

def plot_streamlines(file_path, vector_field_x, vector_field_y): 
    plt.figure() 
    y, x = numpy.mgrid[-2:2:10j, -2:2:10j] 
    plt.streamplot(x, y, vector_field_x, vector_field_y, color='y', cmap=plt.cm.autumn) 
    plt.savefig(file_path + '.png') 
    plt.close() 

这工作正常,但如果我只是改变这一行:

y, x = numpy.mgrid[-2:2:10j, -2:2:10j] 

对那个:

x, y = numpy.mgrid[-2:2:10j, -2:2:10j] 

我得到了一些错误:

Traceback (most recent call last): 
  File "Library/Python/2.7/lib/python/site-packages/matplotlib/pyplot.py", line 3224, in streamplot minlength=minlength, transform=transform) 
  File "/Library/Python/2.7/lib/python/site-packages/matplotlib/axes.py", line 6861, in streamplot transform=transform) 
  File "Library/Python/2.7/lib/python/site-packages/matplotlib/streamplot.py", line 67, in streamplot grid = Grid(x, y) 
  File "Library/Python/2.7/lib/python/site-packages/matplotlib/streamplot.py", line 256, in __init__ 
    assert np.allclose(x_row, x) 
AssertionError 

我不明白如何使用“标准”顺序 x/y,因为我的网格是方形的。此外,如果我的 x 和 y 维度相同,我不知道如何得到这些错误。

如有任何帮助,我们将不胜感激。

谢谢。

请您参考如下方法:

pylab 示例使用 Y,X 然后使用 numpy.mgrid 为流图绘制 X,Y。

import numpy as np 
import matplotlib.pyplot as plt 
 
Y, X = np.mgrid[-3:3:100j, -3:3:100j] 
U = -1 - X**2 + Y 
V = 1 + X - Y**2 
speed = np.sqrt(U*U + V*V) 
 
plt.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn) 
plt.colorbar() 
 
f, (ax1, ax2) = plt.subplots(ncols=2) 
ax1.streamplot(X, Y, U, V, density=[0.5, 1]     
lw = 5*speed/speed.max() 
ax2.streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw) 
 
plt.show() 

取自here .

y,x = numpy.mgrid[-2:2:4j,-2:2:4j] 
x = [[-2.         -0.66666667  0.66666667  2.        ] 
    [-2.         -0.66666667  0.66666667  2.        ] 
    [-2.         -0.66666667  0.66666667  2.        ] 
    [-2.         -0.66666667  0.66666667  2.        ]] 
 
 
y = [[-2.         -2.         -2.         -2.        ] 
     [-0.66666667 -0.66666667 -0.66666667 -0.66666667] 
     [ 0.66666667  0.66666667  0.66666667  0.66666667] 
     [ 2.          2.          2.          2.        ]] 

这似乎与数据在 x 轴和 y 轴、-2,2 等方面的外观有直接关系。类似于 x 轴,y 值类似于 y 轴。