# Source: # https://python.igraph.org/en/stable/tutorials/configuration.html#sphx-glr-tutorials-configuration-py import igraph as ig import matplotlib.pyplot as plt import random # Use the Matplotlib backend ig.config["plotting.backend"] = "matplotlib" ig.config["plotting.layout"] = "fruchterman_reingold" ig.config["plotting.palette"] = "rainbow" random.seed(1) g = ig.Graph.Barabasi(n=100, m=1) betweenness = g.betweenness() colors = [int(i * 200 / max(betweenness)) for i in betweenness] ig.plot(g, vertex_color=colors, vertex_size=15, edge_width=0.3) plt.show()
igraph is a network analysis library with a core written in C, and
python-igraph is its Python interface, imported as igraph. The
algorithms run in compiled code, so it handles large graphs much faster
than pure-Python libraries such as NetworkX. It
covers graph generators, paths, centrality, communities and layouts.
People use it to analyse social, citation and biological networks. This
page is an online igraph compiler: the code runs in your browser, so
you can try it without installing anything.
Run the example first, then paste any snippet below into a new cell to try it.
The ig.config lines make plots use matplotlib, set the default layout
to Fruchterman-Reingold, a force-directed layout, and make colour
numbers refer to the "rainbow" palette. python-igraph takes its random
numbers from Python's random module, so random.seed(1) gives the
same graph on every run. ig.Graph.Barabasi(n=100, m=1) grows a graph
one vertex at a time. Each new vertex links to one existing vertex and
prefers those that already have many links. With m=1 the result is a
tree: 100 vertices and 99 edges. g.betweenness() counts, for each
vertex, how many shortest paths between other vertices pass through
it. The list comprehension scales those counts to colour numbers from 0
to 200, and ig.plot() draws the graph on a matplotlib figure.
Graph.TupleList() builds a graph from (source, target, weight) tuples
and keeps the names in the name vertex attribute. Vertices get IDs
from 0, and g.vs and g.es hold the vertex and edge attributes:
import igraph as ig
g = ig.Graph.TupleList(
[("Home", "School", 10.0), ("Home", "Park", 2.0), ("Park", "School", 1.5),
("Park", "Mall", 3.0), ("Mall", "School", 1.0)],
weights=True,
)
print(g.vcount(), "vertices,", g.ecount(), "edges, directed:", g.is_directed())
print(g.vs["name"]) # vertex attribute
print(g.es["weight"]) # edge attribute
print(dict(zip(g.vs["name"], g.degree())))
print([g.vs[i]["name"] for i in g.neighbors("Park")])
print(g)
get_shortest_path() returns vertex IDs, and distances() returns a
matrix of path lengths. Both count edges unless you pass weights:
import igraph as ig
g = ig.Graph.TupleList(
[("Home", "School", 10.0), ("Home", "Park", 2.0), ("Park", "School", 1.5),
("Park", "Mall", 3.0), ("Mall", "School", 1.0)],
weights=True,
)
path = g.get_shortest_path("Home", "School", weights="weight") # vertex IDs
print([g.vs[i]["name"] for i in path])
print(g.distances("Home", "School", weights="weight")) # 3.5 km
print(g.distances("Home", "School")) # 1 edge
print(g.distances(weights="weight")) # every pair
Graph.Famous("Zachary") is Zachary's karate club, built into igraph:
34 members and the 78 ties between them. betweenness() returns raw
path counts. NetworkX divides by the number of pairs of other vertices,
so vertex 0's 231.1 is 0.438 there:
import igraph as ig
g = ig.Graph.Famous("Zachary")
print(g.vcount(), "vertices,", g.ecount(), "edges")
degree = g.degree()
betweenness = g.betweenness()
pagerank = g.pagerank()
top = sorted(range(g.vcount()), key=lambda v: betweenness[v], reverse=True)[:3]
for v in top:
print(f"vertex {v}: degree {degree[v]}, betweenness {betweenness[v]:.1f}, pagerank {pagerank[v]:.3f}")
community_multilevel() is the Louvain method: it groups vertices so
that most edges fall inside a group. It is randomized, so seed Python's
random module first. Passing a matplotlib Axes as target draws
with matplotlib whatever ig.config says, and mark_groups=True shades
each community:
import random
import igraph as ig
import matplotlib.pyplot as plt
random.seed(0)
g = ig.Graph.Famous("Zachary")
communities = g.community_multilevel()
print(len(communities), "communities, sizes", communities.sizes())
print("modularity", round(communities.modularity, 3))
fig, ax = plt.subplots(figsize=(6, 6))
ig.plot(communities, target=ax, layout=g.layout("fr"), mark_groups=True,
vertex_size=15, vertex_label=range(g.vcount()), vertex_label_size=7)
plt.show()
ig.plot(g) on its own raises AttributeError: Plotting not available. Set ig.config["plotting.backend"] = "matplotlib", as the
example does, or pass target=ax.FakeModule error for the rest of the session. Reload the page and
import both in the same cell, as the example does.name attribute.