how to draw directed graphs using networkx in python? how to draw directed graphs using networkx in python? python python

how to draw directed graphs using networkx in python?


Fully fleshed out example with arrows for only the red edges:

import networkx as nximport matplotlib.pyplot as pltG = nx.DiGraph()G.add_edges_from(    [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),     ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])val_map = {'A': 1.0,           'D': 0.5714285714285714,           'H': 0.0}values = [val_map.get(node, 0.25) for node in G.nodes()]# Specify the edges you want herered_edges = [('A', 'C'), ('E', 'C')]edge_colours = ['black' if not edge in red_edges else 'red'                for edge in G.edges()]black_edges = [edge for edge in G.edges() if edge not in red_edges]# Need to create a layout when doing# separate calls to draw nodes and edgespos = nx.spring_layout(G)nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'),                        node_color = values, node_size = 500)nx.draw_networkx_labels(G, pos)nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)plt.show()

Red edges


I only put this in for completeness. I've learned plenty from marius and mdml. Here are the edge weights. Sorry about the arrows. Looks like I'm not the only one saying it can't be helped. I couldn't render this with ipython notebook I had to go straight from python which was the problem with getting my edge weights in sooner.

import networkx as nximport numpy as npimport matplotlib.pyplot as pltimport pylabG = nx.DiGraph()G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1)G.add_edges_from([('D','A'),('D','E'),('B','D'),('D','E')], weight=2)G.add_edges_from([('B','C'),('E','F')], weight=3)G.add_edges_from([('C','F')], weight=4)val_map = {'A': 1.0,                   'D': 0.5714285714285714,                              'H': 0.0}values = [val_map.get(node, 0.45) for node in G.nodes()]edge_labels=dict([((u,v,),d['weight'])                 for u,v,d in G.edges(data=True)])red_edges = [('C','D'),('D','A')]edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]pos=nx.spring_layout(G)nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)nx.draw(G,pos, node_color = values, node_size=1500,edge_color=edge_colors,edge_cmap=plt.cm.Reds)pylab.show()

enter image description here


Instead of regular nx.draw you may want to use:

nx.draw_networkx(G[, pos, arrows, with_labels])

For example:

nx.draw_networkx(G, arrows=True, **options)

You can add options by initialising that ** variable like this:

options = {    'node_color': 'blue',    'node_size': 100,    'width': 3,    'arrowstyle': '-|>',    'arrowsize': 12,}

Also some functions support the directed=True parameterIn this case this state is the default one:

G = nx.DiGraph(directed=True)

The networkx reference is found here.

Graph with arrows image