Skip to content

Instantly share code, notes, and snippets.

@infinite-Joy
Created September 5, 2017 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save infinite-Joy/0504241d8ff17ade126574e925c8e85c to your computer and use it in GitHub Desktop.
Save infinite-Joy/0504241d8ff17ade126574e925c8e85c to your computer and use it in GitHub Desktop.
%matplotlib inline
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab
# initialise a directed graph
G = nx.DiGraph()
# add the edges and the weights.
G.add_edges_from([('A', 'W')], weight=14)
G.add_edges_from([('A', 'X')], weight=7)
G.add_edges_from([('A', 'Y')], weight=9)
G.add_edges_from([('B', 'W')], weight=9)
G.add_edges_from([('B', 'Z')], weight=6)
G.add_edges_from([('W', 'A')], weight=14)
G.add_edges_from([('W', 'B')], weight=9)
G.add_edges_from([('W', 'Y')], weight=2)
G.add_edges_from([('X', 'A')], weight=7)
G.add_edges_from([('X', 'Y')], weight=10)
G.add_edges_from([('X', 'Z')], weight=15)
G.add_edges_from([('Y', 'A')], weight=9)
G.add_edges_from([('Y', 'W')], weight=2)
G.add_edges_from([('Y', 'X')], weight=10)
G.add_edges_from([('Y', 'Z')], weight=11)
G.add_edges_from([('Z', 'B')], weight=6)
G.add_edges_from([('Z', 'X')], weight=15)
G.add_edges_from([('Z', 'Y')], weight=11)
# value map so that we have different colors for different nodes
val_map = {
'A': 1.0,
'B': 0.9,
'W': 0.8,
'X': 0.7,
'Y': 0.6,
'Z': 0.5
}
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 = [('A','Y'),('Y','W'), ('W', 'B')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]
node_labels = {node:node for node in G.nodes()}
plt.axis('off')
fig = plt.figure(1)
fig = plt.figure(num=1, figsize=(10, 10), dpi=100)
fig.set_size_inches(10.5, 10.5)
# draw it out.
pos=nx.spring_layout(G)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw_networkx_labels(G, pos, labels=node_labels)
nx.draw(G,pos, node_color = values, node_size=1500,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
xmax = 1.2
ymax = 1.1
plt.xlim(-0.1, xmax)
plt.ylim(-0.1, ymax)
pylab.show()
pylab.close()
del fig
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment