建立Matplotlib的LineCollection的细分列表 [英] Building a list of segments for a Matplotlib's LineCollection
问题描述
我想使用matplotlib.collections.LineCollection
对象,从两个Numpy数组x
和y
I want to use a matplotlib.collections.LineCollection
object, starting from the two Numpy arrays x
and y
>>> from matplotlib.collections import LineCollection
>>> from numpy import array, linspace
>>> x = linspace(0, 2, 5)
>>> y = 1-(1-x)**2
实例化LineCollection
的唯一要求是由 segments 的列表组成的数据结构,每个 segment 都是 points的列表,每个 point 是一个元组.
The single thing that's strictly required to instantiate a LineCollection
is a data structure composed of a list of segments, each segment being a list of points, each point being a tuple.
使用我的两个向量x
和y
我可以做到
Using my two vectors x
and y
I can do
>>> 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. ]]]
我的问题.可以用一种不太隐秘的方式构造segments
吗?
My question. Is it possible to construct segments
in a less cryptic manner?
推荐答案
我总是喜欢将线段视为3D数组,第一个轴是线段,第二个是沿线段的坐标,第三个是线段分别是x和y坐标.
I always like to think of the segments as a 3D array, with the first axis being the linesegments, the second being the coordinates along the segments and the third being the x and y coordinates for each.
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)
这篇关于建立Matplotlib的LineCollection的细分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!