Skip to content


To run this notebook in JupyterLab, load examples/ex6_1.ipynb

Warning: this is a work-in-progress draft

Discover community structure using igraph and leidenalg

See also:

Since there are difficulties getting igraph to install correctly across different environments, kglab does not have it as a dependency. Instead you'll need to install the following packages separately:

!pip install python-igraph
!pip install cairocffi
!pip install leidenalg
Requirement already satisfied: python-igraph in /opt/anaconda3/lib/python3.7/site-packages (0.8.3)
Requirement already satisfied: texttable>=1.6.2 in /opt/anaconda3/lib/python3.7/site-packages (from python-igraph) (1.6.3)
Requirement already satisfied: cairocffi in /opt/anaconda3/lib/python3.7/site-packages (1.2.0)
Requirement already satisfied: cffi>=1.1.0 in /opt/anaconda3/lib/python3.7/site-packages (from cairocffi) (1.12.3)
Requirement already satisfied: pycparser in /opt/anaconda3/lib/python3.7/site-packages (from cffi>=1.1.0->cairocffi) (2.19)
Requirement already satisfied: leidenalg in /opt/anaconda3/lib/python3.7/site-packages (0.8.3)
Requirement already satisfied: python-igraph>=0.8.0 in /opt/anaconda3/lib/python3.7/site-packages (from leidenalg) (0.8.3)
Requirement already satisfied: texttable>=1.6.2 in /opt/anaconda3/lib/python3.7/site-packages (from python-igraph>=0.8.0->leidenalg) (1.6.3)

After successful installs, next we'll import the packages:

import igraph as ig
import leidenalg as la

Create a graph based on the Zachary karate club, a famous example used in network science:

G = ig.Graph.Famous("Zachary")

Find a partition, i.e., detect communities with modularity, then plot using python-igraph and cairocffi:

partition = la.find_partition(G, la.ModularityVertexPartition)


Integration with kglab

import kglab

namespaces = {
    "nom":  "",
    "wtm":  "",
    "ind":  "",
    "skos": "",

kg = kglab.KnowledgeGraph(
    name = "A recipe KG example based on",
    base_uri = "",
    namespaces = namespaces,

<kglab.kglab.KnowledgeGraph at 0x10ad6ac50>
sparql = """
    SELECT ?subject ?object
    WHERE {
        ?subject rdf:type wtm:Recipe .
        ?subject wtm:hasIngredient ?object .
import igraph as ig

subgraph = kglab.SubgraphMatrix(kg, sparql)
ig_graph = subgraph.build_ig_graph(ig.Graph())
{'name': '', 'label': ''}

Serialize to GraphML format:

with open("tmp.graphml", "w") as f:

Community detection

component = ig_graph.components().subgraph(0)
partition = la.find_partition(component, la.ModularityVertexPartition)
ig.plot(partition, bbox=(600, 500), vertex_label_size=5, margin=50)


Let's look into the community that involves ind:Butter, nom:Pancake, etc.

ig.plot(partition.subgraph(2), bbox=(600, 500), vertex_label_size=7, margin=50)


Last update: 2021-05-09