ccc
ccc

Reputation: 574

Python - draw a graph with node positions

I'm trying to create a graph with the following information.

    n = 6 #number of nodes
    V = []
    V=range(n)# list of vertices
    print("vertices",V)
    # Create n random points

    random.seed(1)
    points = []
    pos = []

    pos = {i:(random.randint(0,50),random.randint(0,100)) for i in V}
    print("pos =", pos)

This gives my positions as

pos = {0: (8, 72), 1: (48, 8), 2: (16, 15), 3: (31, 97), 4: (28, 60), 5: (41, 48)}

I want to draw a graph with these nodes and some edges(which can be obtained in some other calculation) using Matplotlib in Python. I've tried it as follows. But didn't work.

    G_1 = nx.Graph()
    nx.set_node_attributes(G_1,'pos',pos)
    G_1.add_nodes_from(V) # V is the set of nodes and V =range(6) 


    for (u,v) in tempedgelist:
        G_1.add_edge(v, u, capacity=1) # tempedgelist contains my edges as a list ... ex: tempedgelist =  [[0, 2], [0, 3], [1, 2], [1, 4], [5, 3]]


    nx.draw(G_1,pos, edge_labels=True)
    plt.show()

Can someone please help me with this...

Upvotes: 2

Views: 6999

Answers (3)

andrew_reece
andrew_reece

Reputation: 21264

You only need pos for nx.draw(). You can set both nodes and edges using add_edges_from().

import networkx as nx
import random

G_1 = nx.Graph()
tempedgelist =  [[0, 2], [0, 3], [1, 2], [1, 4], [5, 3]]
G_1.add_edges_from(tempedgelist)

n_nodes = 6
pos = {i:(random.randint(0,50),random.randint(0,100)) for i in range(n_nodes)}
nx.draw(G_1, pos, edge_labels=True)

graph

Note: If you need to track points and positions separately, write into lists from pos:

points = []
positions = []
for i in pos:
    points.append(pos[i])
    positions.append(i)
    positions.append(pos[i])

Upvotes: 4

nos
nos

Reputation: 20862

I don't have a proper IDE right now, but one issue I spot in your code is that pos should be a dictionary, see the networkx doc here for setting node attribute and here for drawing

Try this

import networkx as nx
import matplotlib.pyplot as plt

g= nx.Graph()
pos = {0:(0,0), 1:(1,2)}
g.add_nodes_from(range(2))
nx.set_node_attributes(g, 'pos', pos)
g.add_edge(0, 1)
nx.draw(g, pos, edge_labels=True)
plt.show()

Let me know if it works.

Upvotes: 2

DYZ
DYZ

Reputation: 57033

You must transform your list of positions into a dictionary:

pos = dict(zip(pos[::2],pos[1::2]))

Incidentally, you can build the graph directly from the edge list (the nodes are added automatically):

G1 = nx.Graph(tempedgelist)
nx.set_node_attributes(G_1,'capacity',1)

Upvotes: 1

Related Questions