Python Simple Networkx Example

By | April 2, 2018

Networkx is a python package for creating, visualising and analysing graph networks. This post gives a simple networkx example to show how it works.

A simple Networkx Example

A graph network is built from nodes – the entities of interest, and edges – the relationships between those nodes. To create a graph we need to add nodes and the edges that connect them.

Networkx is capable of operating on graphs with up to 10 million rows and around 100 million edges, but for now we will just create a small example graph.

If we try to create an edge with a node that does not yet exist, networkx will create that node. This means that we can make a simple networkx example with the following code.

import networkx as nx

# Create a networkx graph object
my_graph = nx.Graph() 

# Add edges to to the graph object
# Each tuple represents an edge between two nodes

# Draw the resulting graph
nx.draw(my_graph, with_labels=True, font_weight='bold')

This will produce this output

Simple networkx exampleTaking Things Further

To take things further, there are some extensions and additions you could try, such as:

  • Add new edges between existing nodes
  • Add new edges between existing nodes and new nodes
  • Add new nodes without edges