COMP 200 Resources

[Rice University]

Networkx How-To's

On this page, you can find quick, helpful tips on how to do a variety of common networkx graph tasks for the class.

Quick Links:


Resource links:

Download a single file with the code below:   To use, simply download and import this file:

Create a graph, add nodes & edges

Make an undirected or directed graph object:

import networkx as nx
aGraph = nx.Graph()    # undirected graph
aGraph = nx.DiGraph()  # directed graph	

Add nodes and edges:

aGraph.add_node(aNode) # aNode can be anything that the user wishes to represent a node
aGraph.add_nodes_from(aListOfNodes)   # Add all the nodes from the list, aListOfNodes
aGraph.add_edge(aNode1, aNode2) # creates an edge from aNode1 to aNode2
aGraph.add_edges_from(aListOfNodeTuples)   # Add all the edges in the form of 2-node tuples in the list, aListOfNodeTuples.

Note that adding an edge between two nodes will automatically add any nodes that are not already in the graph.

Plot a networkx Graph Object

There are multiple "layouts" that one can use to plot a graph.   See the networkx documentation for a full list, but here are some common ones:

Be sure to call afterwards to show the plotting window.

Creating, Using and Plotting the Edge Weights in a Weighted Graph

Edge weights values in a Graph object are held as an entry in a dictionaries associated with every edge in the graph.   That is, every edge has a dictionary of the following form:{name:value}.   There is nothing special per se about "weight", it's just one of any possible names that could be used.     Note that the edge can hold multiple named values.

Note: Every node has a similar dictionary of values as well, though by using an object as a node, that data storage is unnecessary since the object itself can hold any desired node information. 

To specify the weight data for an edge:

edgeData = {"weight": 42}      # a dictionary with only one entry
g.add_edge(nodeA, nodeB, edgeData)   #create the edge with the given data dictionary

To retrieve the edge data dictionary:

edgeData = g.get_edge_data(nodeA, nodeB, {"weight": 0})     # if no edge data exists for that node, returns a dictionary with a zero weight value.

Note that networkx supplies some syntactical shortcuts for the above operations, which are may or may not be applicable to a specific situation.   The above technique is the most general.

To create a plot that shows the edge weights:

layout = nx.circular_layout(g)  # or whatever layout you wish	
nx.draw_circular(g)   # draw the graph, must be consistent with layout above
edgeLabels = {}  # dictionary of node tuples to edge labels: {(nodeX, nodeY): aString}
for a, b in collegeGraph.edges():     # loop over all the edges
    edgeLabels[(a, b)] = str(g.get_edge_data(a, b, {"weight":0})["weight"])   # retrieve the edge data dictionary
nx.draw_networkx_edge_labels(g,pos=layout, edge_labels=edgeLabels) # draw the edge labels   # show the plotting window

Note that the above procedure can be generalized to show any edge value(s) you desire.   Also, the code could be shortened by using list comprehensions.


Convert Dictionary Graph Representation into networkx Graph Representation

Given a dictionary based graph representation where the keys are nodes and the the values are lists of successor nodes, the code to convert that type of graph representation into a networkx.DiGraph (directed graph) object is:

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 

Plot a Dictionary Graph Representation

To plot a dictionary-based graph representation, you will need to import matplotlib.pyplot and call a networkx graph drawing function:

import matplotlib.pyplot as plt

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.