Python Matplotlib Streamplot 提供起点

Posted

技术标签:

【中文标题】Python Matplotlib Streamplot 提供起点【英文标题】:Python Matplotlib Streamplot providing start points 【发布时间】:2017-10-11 05:52:00 【问题描述】:

我正在尝试将起点添加到流线图。我找到了一个使用起点here的示例代码;在此链接上讨论了一个不同的问题,但 start_points 参数有效。我从here 抓取了流线型示例代码(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,)

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

【问题讨论】:

Stack Overflow 很愚蠢,不允许我在帖子中添加以下链接:matplotlib.org/devdocs/api/_as_gen/…。从这里我可以看到 start_points 所需的输入,但没有太多其他信息。 【参考方案1】:

example that successfully uses start_points 和example from the matplotlib page 的主要区别在于第一个使用一维数组作为xy 网格,而官方示例使用二维数组。

由于the documentation 明确声明

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()

【讨论】:

太棒了,谢谢。知道在 streamplot 函数中,错误来自这样一个事实,即它无法使用 x[0] 和 y[0] 数组广播 start_points 数组,这更有意义,这是因为这些数组应该只是一维。

以上是关于Python Matplotlib Streamplot 提供起点的主要内容,如果未能解决你的问题,请参考以下文章

python安装matplotlib:python -m pip install matplotlib报错

python如何安装matplotlib模块

python--matplotlib

Python之matplotlib基础

怎么安装python matplotlib

4.1Python??????????????????Matplotlib??????(???)---??????Matplotlib