user2591113
user2591113

Reputation: 11

plotting lines in pairs

I'm working on a network project in which I need to draw lines (edges) between pairs of points (nodes). Currently I'm using matplotlib.pyplot for this, but the problem is that pyplot.plot(x, y) starts at (x[0], y[0]) and then continues to (x[1], y[1]) etc.
I have a separate list of tuples for the connections of the nodes:
edges=[(0,1), (0,2), (3,2), (2,1)...(m,n)], which refers to indices of the separate nodes. The problem is that I need to animate the thing with matplotlib.animation.

To just add lines between nodes (static picture) I was using ax.add_line(Line2D([x1, x2], [y1, y2])), but I can't figure out how to get this method to work with animation.FuncAnimation().

Some dummy code:

import matplotlib.pyplot as plt

edges = [(0,1), (2,3), (3,0), (2,1)]

x = [-5, 0, 5, 0]
y = [0, 5, 0, -5]

lx = []
ly = []
for edge in edges:
    lx.append(x[edge[0]])
    lx.append(x[edge[1]])
    ly.append(y[edge[0]])
    ly.append(y[edge[1]])

plt.figure()
plt.plot(x, y, 'ro')
plt.plot(lx, ly, '-', color='#000000')
plt.show()

(Image of this and the next example below)

If I instead use the following:

import matplotlib.pyplot as plt
from pylab import Line2D, gca

edges = [(0,1), (2,3), (3,0), (2,1)]

x = [-5, 0, 5, 0]
y = [0, 5, 0, -5]

plt.figure()
ax = gca()
for edge in edges:
    ax.add_line(Line2D([x[edge[0]], x[edge[1]]], [y[edge[0]], y[edge[1]]], color='#000000'))

ax.plot(x, y, 'ro')
plt.show()

it all works the way I need: Examples.
Unfortunately, this is not possible (afaik) during animation. What I need then is is a way to plot lines between individual pairs of nodes.

Very bad problem formulation, I know, but I hope that someone understands and is able to help.

Thank you!

Upvotes: 1

Views: 4888

Answers (1)

ev-br
ev-br

Reputation: 26030

>>> edges=[(0,1), (0,2), (3,2), (2,1)]
>>> 
>>> xx = [x[0] for x in edges]
[0, 0, 3, 2]
>>> yy = [x[1] for x in edges]
[1, 2, 2, 1]
>>> line, = ax.plot(xx, yy, 'ro-')

Then just feed this to plot and animate the result. Here's one example (there are many).

Upvotes: 1

Related Questions