pheon
pheon

Reputation: 3009

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

This is what I get

@CactusWoman gives a way that works. 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()

Upvotes: 0

Views: 3055

Answers (3)

C_Z_
C_Z_

Reputation: 7796

You probably want lineCollection for this. 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.

Upvotes: 1

SirParselot
SirParselot

Reputation: 2700

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

Upvotes: 0

Jared Goguen
Jared Goguen

Reputation: 9010

This might be a more Pythonic solution:

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.

Upvotes: 1

Related Questions