...

/

Saving and Plotting Networks with NetworkX

Saving and Plotting Networks with NetworkX

Learn how to save, load, and plot networks using the NetworkX library.

Visualizing networks is not always possible, but when it is, we can generate some good insights into our analysis. Also, the ability to load and save networks to files is essential to sharing and obtaining data. This is why, in this lesson, we’re going to explore how to do those things with NetworkX.

Plotting with NetworkX

To plot with NetworkX, we need to import the matplotlib library too:

Press + to interact
import matplotlib.pyplot as plt

The most straightforward way of plotting anything in NetworkX is to use the nx.draw() function. Let’s define a simple graph and see how it works.

Press + to interact
import networkx as nx
import matplotlib.pyplot as plt
example = [
(0, 1),
(0, 3),
(2, 3),
(3, 5),
(1, 4)
]
G = nx.Graph()
G.add_edges_from(example)
nx.draw(G)
  • Line 15: This is where we ask NetworkX to plot our graph.

Plotting with labels

This plot, however, is not very informative. We can improve it by asking NetworkX to also plot ...