Configuring Ubuntu for Python Development

Using Networkx to draw graph

Author posted @ 2014年4月13日 14:51 in Python , 9232 阅读

Draw a directed graph using Networkx 

Code :

    import matplotlib.pyplot as plt

import networkx as nx

# Add nodes by specifying their positions
G.add_node('10', pos=(2, 10))
G.add_node('9',  pos=(4, 9))
G.add_node('8',  pos=(0, 13))
G.add_node('7',  pos=(1.5, 4))
G.add_node('6',  pos=(4, 4))
G.add_node('5',  pos=(6, 11))
G.add_node('3',  pos=(6, 6))
G.add_node('0',  pos=(0, 0))
# Add edges by defining weight and label
G.add_edge('10','9',weight=1, label='I')
G.add_edge('10','8',weight=1, label='I')
G.add_edge('10','7',weight=1, label='I')
G.add_edge('9','3', weight=1, label='I')
G.add_edge('9','6',weight=1, label='I')
G.add_edge('9','5',weight=1, label='I')
G.add_edge('7','0',weight=1, label='I')
G.add_edge('7','6',weight=0, label='II')
G.add_edge('6','3',weight=0, label='II')
G.add_edge('5','3',weight=0, label='II')

elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.5] # solid edge
esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.5] # dashed edge

# Retrieve the positions from graph nodes and save to a dictionary
# Draw nodes
nx.draw_networkx_nodes(G,pos,node_size=700, node_color='orange')

# Draw edges
nx.draw_networkx_edges(G,pos,edgelist=elarge, width=2, edge_color='g')
nx.draw_networkx_edges(G,pos,edgelist=esmall, arrows=False, width=3,

# Draw node labels

# Draw edge labels
edge_labels =dict([((u, v), d['label']) 
                   for u, v, d in G.edges(data=True)])

nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)

plt.savefig("communication_authority_graph.eps", format='eps') # save as eps # display


  1. draw_networkx_nodes 
  2. draw_networkx_edges
  3. draw_networkx_labels
  4. how to draw graph edges with labels

登录 *

loading captcha image...
or Ctrl+Enter