## Part 1 – Networkx Basics

`networkx`

is a powerful python package that allows you to easily work with graphs in Python. Combining it with the `matplotlib.pyplot`

package even makes it simple to draw graphs. This is very useful when learning or teaching about **graphs for A Level Computer Science.**

1 2 3 |
# Auto formatting - completely optional, requires installation. %load_ext nb_black |

### Setup

1 2 3 4 5 |
import networkx as nx G = nx.Graph() print(G.nodes(), G.edges()) |

1 2 |
[] [] |

### Nodes

1 2 3 |
G.add_node("A") print(G.nodes()) |

1 2 |
['A'] |

1 2 3 4 |
G.add_nodes_from(["B", "C"]) print(G.nodes()) print("Number of nodes in graph: ", G.number_of_nodes()) |

1 2 3 |
['A', 'B', 'C'] Number of nodes in graph: 3 |

### Edges

OK so now let’s look at how we add edges to our graph.

1 2 3 4 5 6 7 |
G.clear() # First we clear the graph so we can start fresh G.add_nodes_from(["A", "B", "C"]) G.add_edge("A", "B", weight=5) G.add_edge("B", "C", weight=7) G.add_edge("C", "A", weight=2) print(G.nodes(), G.edges()) |

1 2 |
['A', 'B', 'C'] [('A', 'B'), ('A', 'C'), ('B', 'C')] |

### The Fun Part – Drawing Your Graph

Now we get to draw our graph. They say a picture is worth a thousand words and I agree. Python makes this super easy for us with just a couple of lines of code.

1 2 3 4 5 6 7 8 9 10 11 12 |
%matplotlib inline import matplotlib.pyplot as plt pos = nx.spring_layout(G) weights = nx.get_edge_attributes(G, "weight") nx.draw_networkx(G, pos, with_labels=True) nx.draw_networkx_edge_labels(G, pos, edge_labels=weights) plt.title("Basic Graphs with Networkx") plt.gcf().canvas.set_window_title("") plt.show() |

I for one am pretty impressed by the `networkx`

package. This article covers just the very basics, but already we have drawn a weighted graphs and learned how to add nodes and edges to an existing graph using `networkx`

‘s powerful functionality.

Here’s the complete listing for this example, for your convenience:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import matplotlib.pyplot as plt import networkx as nx import numpy as np G = nx.Graph() # Create empty graph G.add_nodes_from(["A", "B", "C"]) # Add nodes # Add edges G.add_edge("A", "B", weight=5) G.add_edge("B", "C", weight=7) G.add_edge("C", "A", weight=2) # Create drawing pos = nx.spring_layout(G) # List of positions of nodes weights = nx.get_edge_attributes(G, "weight") # List of weights nx.draw_networkx(G, pos, with_labels=True) nx.draw_networkx_edge_labels(G, pos, edge_labels=weights) plt.title("Basic Graphs with Networkx") plt.gcf().canvas.set_window_title("") # Hide window title # Display Graph plt.show() |