gpt4 book ai didi

numpy - 为 Matplotlib 的 LineCollection 构建段列表

转载 作者:行者123 更新时间:2023-12-02 19:48:04 24 4
gpt4 key购买 nike

我想使用一个 matplotlib.collections.LineCollection 对象,从两个 Numpy 数组 xy 开始

>>> from matplotlib.collections import LineCollection
>>> from numpy import array, linspace

>>> x = linspace(0, 2, 5)
>>> y = 1-(1-x)**2

实例化 LineCollection 严格要求的唯一一件事是由列表组成的数据结构,每个都是一个列表,每个都是一个元组。

使用我的两个向量xy我可以做到

>>> segments = np.array(list(zip( zip(x, x[1:]), zip(y, y[1:])))) .transpose((0,2,1))
>>> print(segments)
[[[0. 0. ]
[0.5 0.75]]

[[0.5 0.75]
[1. 1. ]]

[[1. 1. ]
[1.5 0.75]]

[[1.5 0.75]
[2. 0. ]]]

我的问题。是否可以以一种不太神秘的方式构造

最佳答案

我总是喜欢将线段视为 3D 数组,第一个轴是线段,第二个轴是沿线段的坐标,第三个轴是每个线段的 x 和 y 坐标。

points = np.array([x, y]).T.reshape(-1,1,2)
segments = np.concatenate([points[:-1],points[1:]], axis=1)

或者同样,

segments = np.stack((np.c_[x[:-1],x[1:]],np.c_[y[:-1],y[1:]]), axis=2)

关于numpy - 为 Matplotlib 的 LineCollection 构建段列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58879013/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com