How to Plot a Network Graph in Python with NetworkX

Draw network graphs in Python with NetworkX and Matplotlib, then make them interactive with pyvis.

To plot a network graph in Python, build the graph with NetworkX, compute node positions with a layout function such as nx.kamada_kawai_layout(), and draw it on a Matplotlib axes with nx.draw_networkx(). For a draggable, zoomable version, pass the same graph to pyvis.

Install both with pip install networkx pyvis. The examples use NetworkX 3.7 and pyvis 0.3.2.

Quick Example

NetworkX ships with a graph of which characters appear together in Les Misérables. This draws it with node size set by the number of connections, line width set by how often two characters share a chapter, and labels on the best-connected characters.

import matplotlib.pyplot as plt
import networkx as nx

G = nx.les_miserables_graph()
pos = nx.kamada_kawai_layout(G, weight=None)

degree = dict(G.degree())
main = [n for n in G if degree[n] >= 15]

fig, ax = plt.subplots(figsize=(10, 7.5))
nx.draw_networkx_edges(G, pos, ax=ax, alpha=0.25,
                       width=[0.4 + d["weight"] / 5 for *_, d in G.edges(data=True)])
nx.draw_networkx_nodes(G, pos, ax=ax, node_color="#e76f51", edgecolors="white",
                       node_size=[25 * degree[n] for n in G])
nx.draw_networkx_labels(G, pos, ax=ax, labels={n: n for n in main}, font_size=9,
                        bbox=dict(facecolor="white", alpha=0.75, edgecolor="none", pad=1))
ax.set_title("Character co-occurrence in Les Misérables")
ax.axis("off")
fig.tight_layout()
plt.show()

Network graph of Les Misérables characters. Valjean is the largest node near the center, with Javert, Thenardier, Marius, Gavroche, Enjolras and Fantine also labeled

The graph has 77 characters (nodes) and 254 connections (edges). Valjean has the most, with 36.

Drawing nodes, edges, and labels with separate functions gives you control over each layer. Lists passed to node_size and node_color must follow the order of the nodes in G, and a width list follows the order of G.edges().

Create a Network Graph from a Pandas DataFrame

nx.from_pandas_edgelist() builds a graph from a DataFrame with one row per connection. Use create_using=nx.DiGraph when direction matters, and the edges are drawn with arrows. Here each row is a package and one of the packages it depends on:

import pandas as pd

edges = pd.DataFrame({
    "source": ["pandas", "pandas", "seaborn", "seaborn", "seaborn",
               "matplotlib", "scipy", "scikit-learn", "scikit-learn", "statsmodels",
               "statsmodels", "statsmodels"],
    "target": ["numpy", "python-dateutil", "numpy", "pandas", "matplotlib",
               "numpy", "numpy", "numpy", "scipy", "numpy", "pandas", "scipy"],
})

D = nx.from_pandas_edgelist(edges, "source", "target", create_using=nx.DiGraph)

dpos = {}
for layer, names in enumerate(nx.topological_generations(D)):
    for i, name in enumerate(sorted(names)):
        dpos[name] = (i - (len(names) - 1) / 2, -layer)  # first layer on top

fig, ax = plt.subplots(figsize=(9, 5.5))
nx.draw_networkx(D, dpos, ax=ax, node_size=2200, node_color="#bde0fe",
                 edge_color="#6c757d", arrowsize=18, font_size=9)
ax.set_title("A few direct dependencies between data packages")
ax.margins(0.12)
ax.axis("off")
fig.tight_layout()
plt.show()

Directed network graph in three rows. statsmodels, scikit-learn and seaborn point down to pandas, matplotlib and scipy, which point down to numpy and python-dateutil

For a hierarchy like this, topological_generations() splits any directed graph without cycles into layers, and the loop gives each layer its own row. NetworkX also has multipartite_layout() for this, but in our runs with 3.7 the order within a row could change between runs. numpy has the most incoming edges, 6.

If your DataFrame has a weight column, add edge_attr="weight" to keep it on the edges.

Which NetworkX Layout Should I Use?

The layout decides where nodes go, and it changes how readable the graph is far more than any styling.

layouts = {
    "spring_layout": nx.spring_layout(G, seed=8),
    "kamada_kawai_layout": nx.kamada_kawai_layout(G, weight=None),
    "circular_layout": nx.circular_layout(G),
    "spectral_layout": nx.spectral_layout(G),
}

fig, axes = plt.subplots(2, 2, figsize=(10, 9))
for ax, (name, p) in zip(axes.flat, layouts.items()):
    nx.draw_networkx(G, p, ax=ax, node_size=30, node_color="#264653",
                     edge_color="#adb5bd", width=0.6, with_labels=False)
    ax.set_title(name)
fig.tight_layout()
plt.show()

The same graph in four layouts. Spring and Kamada-Kawai show clusters, circular puts every node on a ring with crossing edges, and spectral crushes most nodes into one corner

Layout Good for
kamada_kawai_layout Small to medium graphs, where it spreads nodes evenly
spring_layout A general default that pulls connected nodes together
circular_layout Small graphs where the pattern of links matters more than clusters
multipartite_layout Layered or grouped nodes, such as pipelines
spectral_layout Regular structures such as grids. It performs poorly on this graph

Two details catch people out:

  • spring_layout() starts from random positions, so pass seed= to get the same picture every run.
  • Edge weights mean opposite things in two of these functions. spring_layout() treats a larger weight as a stronger pull, while kamada_kawai_layout() treats it as a longer distance. The examples here pass weight=None to Kamada-Kawai so that frequent co-occurrence doesn't push characters apart.

If nodes in a spring_layout() graph bunch together, raise k (the preferred distance between nodes), for example k=0.6.

Color Nodes by Community

nx.community.louvain_communities() groups nodes that are densely connected to each other. Give each group a color and label its best-connected member:

communities = nx.community.louvain_communities(G, weight="weight", seed=42)
palette = ["#0077b6", "#f4a261", "#2a9d8f", "#e63946", "#8d5fd3", "#8a8d00"]
color_of = {n: palette[i] for i, group in enumerate(communities) for n in group}
leaders = [max(sorted(group), key=degree.get) for group in communities]

fig, ax = plt.subplots(figsize=(10, 7.5))
nx.draw_networkx_edges(G, pos, ax=ax, alpha=0.2)
nx.draw_networkx_nodes(G, pos, ax=ax, node_color=[color_of[n] for n in G],
                       node_size=[25 * degree[n] for n in G], edgecolors="white")
nx.draw_networkx_labels(G, pos, ax=ax, labels={n: n for n in leaders}, font_size=11,
                        font_weight="bold",
                        bbox=dict(facecolor="white", alpha=0.8, edgecolor="none", pad=1))
ax.set_title(f"{len(communities)} communities found with the Louvain method")
ax.axis("off")
fig.tight_layout()
plt.show()

Les Misérables network colored by six communities, labeled Myriel, Fantine, Bamatabois, Thenardier, Valjean and Gavroche

The largest groups are those around Valjean (25 characters) and Gavroche (17). Louvain has a random element, so the number of groups can change with a different seed. The palette above has six colors to match this result.

To rank nodes by how often they sit on the shortest path between others, use nx.betweenness_centrality():

centrality = nx.betweenness_centrality(G)
for name, score in sorted(centrality.items(), key=lambda item: -item[1])[:3]:
    print(f"{name}: {score:.2f}")
Valjean: 0.57
Myriel: 0.18
Gavroche: 0.17

Myriel ranks second despite having only 10 connections, because several characters reach the rest of the graph only through them.

Interactive Network Graph with pyvis

pyvis turns a NetworkX graph into an HTML page where you can drag nodes, zoom, and hover for details. It reads node attributes named size, color, and title (the tooltip).

from pyvis.network import Network

H = G.copy()
for n in H:
    H.nodes[n].update(size=30 + 4 * degree[n], color=color_of[n],
                      title=f"{n} (degree {degree[n]})")

net = Network(height="500px", width="100%", cdn_resources="remote")
net.from_nx(H)
net.barnes_hut(spring_length=100, central_gravity=1.0)
net.write_html("les-miserables-network.html")
  • Pass a copy to from_nx(). It modifies the graph it's given, adding a size to every node and renaming each edge's weight to width.
  • cdn_resources="remote" loads the JavaScript from a CDN. The default, "local", writes a lib/ folder next to the HTML file that has to travel with it.
  • In Jupyter, create the network with Network(notebook=True, cdn_resources="in_line") and call net.show("graph.html").

pyvis hasn't had a release since 0.3.2 in 2023. It works here, but keep that in mind for long-lived projects.

NetworkX or pyvis?

Use When
NetworkX with Matplotlib Static figures for papers and reports, with up to a few hundred nodes
pyvis Exploring a graph by hovering and dragging, or sharing it as a web page

NetworkX is mainly a graph analysis library, and its drawing functions are intentionally basic. For very large graphs, a dedicated tool such as Gephi or Graphviz will cope better.

Similar Topics