简体   繁体   中英

How to plot graph consisted of line segments between two points using matplotlib

I have network edges defined between 4 points, as : edges = [(2, 5), (2, 4), (2, 3),(3, 5),(3, 4),(3, 2),(4, 5),(4, 4),(4, 2),(4, 3),(5, 4),(5, 2),(5, 3)]

I want to plot a graph using these edges. The coordinates of these 4 points are given as:

a = [ 1 0 -1 0]

b = [0, 1, 0, -1]

Here is the function I wrote:

def plot_current_graph(a,b, edges):

for i in range(0, len(a)):
    plt.plot(a,b,'ro')

xc = []
yc = []
for i in range(0, len(edges)):
    xc.append(a[edges[i][0]-2])
    xc.append(a[edges[i][1]-2])
    #print xc
    yc.append(b[edges[i][0]-2])
    yc.append(b[edges[i][1]-2])

for i in range(0, len(edges), 2):
    plt.plot(xc[i:i+2], yc[i:i+2], 'ro-')


plt.axis('equal')
plt.show()
plt.pause(1)
plt.clf()

I expected to see a figure with all edges connecting 4 points, but instead this function plots one by one edge on a separate figure. How can I get only one figure with all edges on the figure plotted at the same time? I'm trying to use this function in a program that periodically plots new figure when the edges change.

Thanks!

This may give you what you're after:

edges = [(2, 5), (2, 4), (2, 3),(3, 5),(3, 4),(3, 2),(4, 5),(4, 4),(4, 2),(4, 3),(5, 4),(5, 2),(5, 3)]
a = [1, 0, -1, 0]
b = [0, 1, 0, -1]

def plot_current_graph(a,b, edges):

    for i in range(0, len(a)):
        plt.plot(a,b,'ro')

    xc = []
    yc = []
    for i in range(0, len(edges)):
        xc.append(a[edges[i][0]-2])
        xc.append(a[edges[i][1]-2])
        #print xc
        yc.append(b[edges[i][0]-2])
        yc.append(b[edges[i][1]-2])

    for i in range(0, len(edges), 2):
        plt.plot(xc[i:i+2], yc[i:i+2], 'ro-')


        plt.axis('equal')
        plt.show()
        plt.pause(1)

plot_current_graph(a, b, edges)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM