Python Matplotlib Streamplot 提供起点

JWi*_*Wil 2 python plot matplotlib valueerror

我正在尝试将起点添加到流线图中。我在这里找到了一个使用起点的示例代码;在此链接中讨论了一个不同的问题,但 start_points 参数有效。我从这里获取了流线型示例代码(images_contours_and_fields 示例代码:streamplot_demo_features.py)。我不明白为什么我可以在一个代码中而不是另一个中定义起点。当我尝试在示例代码 (streamplot_demo_features.py) 中定义起点时,出现以下错误:

    Traceback (most recent call last):

  File "<ipython-input-79-981cad64cff6>", line 1, in <module>
    runfile('C:/Users/Admin/.spyder/StreamlineExample.py', wdir='C:/Users/Admin/.spyder')

  File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users/Admin/.spyder/StreamlineExample.py", line 28, in <module>
    ax1.streamplot(X, Y, U, V,start_points=start_points)

  File "C:\ProgramData\Anaconda2\lib\site-packages\matplotlib\__init__.py", line 1891, in inner
    return func(ax, *args, **kwargs)

  File "C:\ProgramData\Anaconda2\lib\site-packages\matplotlib\axes\_axes.py", line 4620, in streamplot
    zorder=zorder)

  File "C:\ProgramData\Anaconda2\lib\site-packages\matplotlib\streamplot.py", line 144, in streamplot
    sp2[:, 0] += np.abs(x[0])

ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (100,)
Run Code Online (Sandbox Code Playgroud)

我注意到网络上没有太多关于使用 start_points 的方法,因此任何其他信息都会有所帮助。

Imp*_*est 5

成功使用start_points示例与来自 matplotlib 页面示例之间的主要区别在于,第一个使用一维数组作为xy网格,而官方示例使用二维数组。

由于文档明确指出

x, y: 一维数组,均匀间隔的网格。

我们可能会坚持使用一维数组。不清楚为什么这个例子与文档相矛盾,但我们可以简单地忽略它。

现在,使用一维数组作为网格,start_points按预期工作,因为它需要一个 2 列数组(第一列 x 坐标,第二列 y 坐标)。

一个完整的例子:

import numpy as np
import matplotlib.pyplot as plt

x,y = np.linspace(-3,3,100),np.linspace(-3,3,100)
X,Y = np.meshgrid(x,y)
U = -1 - X**2 + Y
V = 1 + X - Y**2
speed = np.sqrt(U*U + V*V)

start = [[0,0], [1,2]]

fig0, ax0 = plt.subplots()

strm = ax0.streamplot(x,y, U, V, color=(.75,.90,.93))
strmS = ax0.streamplot(x,y, U, V, start_points=start, color="crimson", linewidth=2)

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

在此处输入图片说明