python-igraph Manual

For using igraph from Python

Quick Start

Quick Start

For the eager folks out there, this intro will give you a quick overview of the following operations:

  • Construct a graph

  • Set attributes of nodes and edges

  • Plot a graph using matplotlib

  • Save the plot as an image

  • Export and import a graph as a .gml file

To find out more features that igraph has to offer, check out the Gallery!

import igraph as ig
import matplotlib.pyplot as plt

# Construct a graph with 3 vertices
n_vertices = 3
edges = [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (3, 4)]
g = ig.Graph(n_vertices, edges)

# Set attributes for the graph, nodes, and edges
g["title"] = "Small Social Network"
g.vs["name"] = ["Daniel Morillas", "Kathy Archer", "Kyle Ding", "Joshua Walton", "Jana Hoyer"]
g.vs["gender"] = ["M", "F", "F", "M", "F"]["married"] = [False, False, False, False, False, False, False, True]

# Set individual attributes
g.vs[1]["name"] = "Kathy Morillas"[0]["married"] = True

# Plot in matplotlib
# Note that attributes can be set globally (e.g. vertex_size), or set individually using arrays (e.g. vertex_color)
fig, ax = plt.subplots(figsize=(5,5))
    layout="circle", # print nodes in a circular layout
    vertex_color=["steelblue" if gender == "M" else "salmon" for gender in g.vs["gender"]],
    edge_width=[2 if married else 1 for married in["married"]],
    edge_color=["#7142cf" if married else "#AAA" for married in["married"]]

# Save the graph as an image file

# Export and import a graph as a GML file."social_network.gml")
g = ig.load("social_network.gml")

The output of the code is pictured below

The visual representation of a small friendship group

The Output Graph