import networkx as nx
import matplotlib.pyplot as plt
##--- networkx utility functions ---------
def dict2nx(aDictGraph):
""" Converts the given dictionary representation of a graph,
aDictGraph, into a networkx DiGraph (directed graph) representation.
aDictGraph is a dictionary that maps nodes to its
neighbors (successors): {node:[nodes]}
A DiGraph object is returned.
"""
g = nx.DiGraph()
for node, neighbors in aDictGraph.items():
g.add_node(node) # in case there are nodes with no edges
for neighbor in neighbors:
g.add_edge(node, neighbor)
return g
def plot_graph(aDictGraph, plotTitle):
""" Plots a dictionary representation of a graph,
aDictGraph, including the given plot title.
Opens a modal plot window that will stop program execution
until it is closed.
"""
plt.title(plotTitle)
nx.draw_spring(dict2nx(aDictGraph))
plt.show()
# Test code. Uncomment the following lines to use
#dict_graph = { 'a':['b', 'c', 'd'], 'b':['a', 'c'], 'c':['d'], 'd':['a']}
#plot_graph(dict_graph, "A Test Graph")