File: visualize_communities.py

package info (click to toggle)
python-igraph 0.11.9%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 3,480 kB
  • sloc: ansic: 24,611; python: 21,748; sh: 111; makefile: 35; sed: 2
file content (67 lines) | stat: -rw-r--r-- 1,751 bytes parent folder | download | duplicates (3)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
.. _tutorials-visualize-communities:

=====================
Communities
=====================

This example shows how to visualize communities or clusters of a graph.
"""
import igraph as ig
import matplotlib.pyplot as plt

# %%
# First, we generate a graph. We use a famous graph here for simplicity:
g = ig.Graph.Famous("Zachary")

# %%
# Edge betweenness is a standard way to detect communities. We then covert into
# a :class:`igraph.VertexClustering` object for subsequent ease of use:
communities = g.community_edge_betweenness()
communities = communities.as_clustering()

# %%
# Next, we color each vertex and edge based on its community membership:
num_communities = len(communities)
palette = ig.RainbowPalette(n=num_communities)
for i, community in enumerate(communities):
    g.vs[community]["color"] = i
    community_edges = g.es.select(_within=community)
    community_edges["color"] = i


# %%
# Last, we plot the graph. We use a fancy technique called proxy artists to
# make a legend. You can find more about that in matplotlib's
# :doc:`matplotlib:users/explain/axes/legend_guide`:
fig, ax = plt.subplots()
ig.plot(
    communities,
    palette=palette,
    edge_width=1,
    target=ax,
    vertex_size=20,
)

# Create a custom color legend
legend_handles = []
for i in range(num_communities):
    handle = ax.scatter(
        [], [],
        s=100,
        facecolor=palette.get(i),
        edgecolor="k",
        label=i,
    )
    legend_handles.append(handle)
ax.legend(
    handles=legend_handles,
    title='Community:',
    bbox_to_anchor=(0, 1.0),
    bbox_transform=ax.transAxes,
)
plt.show()

# %%
# For an example on how to generate the cluster graph from a vertex cluster,
# check out :ref:`tutorials-cluster-graph`.