Skip to content Skip to sidebar Skip to footer

Networkx: Drawing Graph

I am trying to draw a graph using NetworkX in Python. I am using the following code: G=nx.to_networkx_graph(adj) pos=nx.spring_layout(G) #G=nx.path_graph(8) nx.draw(G,pos,labels)

Solution 1:

So for the positioning, you've set pos based on spring_layout. pos gives the positions of your nodes. Check it out - once you've defined it, ask python to print pos for you and see what it's doing.

Here's an alternative code:

import networkx as nx
import pylab as py
blue_edges = [('B', 'C'), ('B', 'D'), ('B', 'E'), ('E', 'F')]
red_edges = [('A', 'B'), ('A', 'C'), ('C', 'E'), ('D', 'E'), ('D', 'F')]

G=nx.Graph() #define G
G.add_edges_from(blue_edges)
G.add_edges_from(red_edges)

pos = {'A':(0,0), 'B':(1,1), 'C':(1,-1), 'D':(2,1), 'E':(2,-1), 'F':(3,0)}

nx.draw_networkx(G, pos=pos, edgelist = [], node_color = 'k')
nx.draw_networkx(G, pos=pos, nodelist = [], edgelist = blue_edges, edge_color = 'b')
nx.draw_networkx(G, pos=pos, nodelist = [], edgelist = red_edges, edge_color = 'r')

enter image description here

and if you want it without the x and y axes showing, change the last bit to:

nx.draw(G, pos=pos, edgelist = [], node_color = 'k')
nx.draw(G, pos=pos, nodelist = [], edgelist = blue_edges, edge_color = 'b')
nx.draw(G, pos=pos, nodelist = [], edgelist = red_edges, edge_color = 'r')

enter image description here

Post a Comment for "Networkx: Drawing Graph"