[英]In python, drawing a list of line segments given their indices
Given a list of vertices, and a list of line segments (indices which refer to the vertices of a segment), what's the best way of drawing all the lines segments where they may not form a continuous line? 给定一个顶点列表和一个线段列表(引用线段顶点的索引),绘制所有可能不形成连续线的线段的最佳方法是什么?
I can do it this way, but it's obviously clunky; 我可以这样做,但是显然很笨拙。 is there a better way? 有没有更好的办法?
vertices=[[0,0],[1,1],[1,2],[4,1]]
segs=[[0,1],[0,2],[2,3]]
for seg in segs:
x = vertices[seg[0]][0], vertices[seg[1]][0]
y = vertices[seg[0]][1], vertices[seg[1]][1]
plot(x, y, 'k')
@CactusWoman gives a way that works. @CactusWoman提供了一种可行的方法。 This is the full code. 这是完整的代码。
import matplotlib
import matplotlib.collections
import matplotlib.pyplot
vertices=[[0,0],[1,1],[1,2],[4,1]]
segs=[[0,1],[0,2],[2,3]]
lines = [[tuple(vertices[j]) for j in i]for i in segs]
lc = matplotlib.collections.LineCollection(lines)
fig, ax = matplotlib.pyplot.subplots()
ax.add_collection(lc)
matplotlib.pyplot.xlim([0,4])
matplotlib.pyplot.ylim([0,2])
matplotlib.pyplot.show()
This might be a more Pythonic solution: 这可能是更Python化的解决方案:
for v1,v2 in segs:
x,y = zip(vertices[v1],vertices[v2])
plot(x,y,'k')
Assuming that I understand what you're trying to do. 假设我了解您要执行的操作。 Since they are not necessarily continuous, I think you're going to have to iterate over segs
and plot them individually no matter what. 由于它们不一定是连续的,我想你将不得不遍历segs
并分别绘制他们不管。
You probably want lineCollection
for this. 您可能需要lineCollection
。 Give it a list of lists of tuples, where each tuple is a vertex and each list contains all vertices of a segment. 给它一个元组列表的列表,其中每个元组是一个顶点,每个列表包含一个线段的所有顶点。
lines = [[tuple(vertices[j]) for j in i]for i in segs]
lc = matplotlib.collections.LineCollection(lines)
Then use add_collection
to add it to your axes. 然后使用add_collection
将其添加到您的轴上。
I don't know if this is much better but you could zip your vertices and segs and loop over them like so. 我不知道这是否更好,但是您可以压缩顶点和段并像这样遍历它们。
vertices=[[0,0],[0,1],[3,2]]
segs=[[0,1],[0,2],[2,3]]
for v,s in zip(vertices, segs):
x = v[0], s[0]
y = v[1], s[1]
plot(x,y,'k')
I'm not sure I totally understand your code but you will get an error since you are trying to access an index that doesn't exist. 我不确定我是否完全理解您的代码,但是由于尝试访问不存在的索引,您会收到错误消息。 This is just a 1:1 relationship. 这只是一对一的关系。 index x
vertices to index x
segs 索引x
顶点以索引x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.