VOOZH about

URL: https://ironpdf.com/python/blog/python-help/igraph-python/

⇱ igraph python (How it Works for Developers)


Skip to footer content
  1. IronPDF for Python
  2. IronPDF for Python Blog
  3. Python Help
  4. igraph python
PYTHON HELP

igraph python (How it Works for Developers)

Graphs and complex network research are basic notions of computer science and mathematics used to model complex linkages and interactions. The nodes, sometimes also called vertices, and edges, sometimes referred to as links, of a graph are, in essence, merely visual representations and interpretations of an entity and its relationships, shown through the edges that connect nodes.

More generally, all the graphs used for transportation systems, social networks, and communication networks are considered to be networks. By looking at graphs and networks, we can understand and overcome problems related to connectivity, flow, and network structure. Such work provides insight into a diversity of fields, from social dynamics and organizational structure to algorithms for efficient routing and optimization. These concepts are very central in network theory, operations research, and data science.

In this article, we use igraph to show how you can generate network graphs and print them into a PDF file using the flexible and reliable IronPDF library.

What is igraph?

Igraph is a strong Python package for generating, manipulating, and analyzing complex graphs and networks. It provides an enormous toolkit to deal with graphs, from generation to manipulation and their visualization. Python igraph facilitates the implementation of network analysis through many algorithms computing various metrics of centrality, shortest paths, community structure, and even more.

This library thus provides good visualization with adaptive layouts and properties for directed and undirected graphs. Igraph is very flexible and fast, and it is often found in applications for the analysis of difficult relational data, such as in data science, computational biology, and social network studies.

πŸ‘ igraph python (How it Works for Developers): Figure 1 - Igraph webpage

Setting Up and Using the igraph Python Package

To begin with fundamental graph theory operations and configurations in Python, use the following steps to create, configure, and use igraph for yourself.

Installing the igraph Package

You must install the igraph package first. The following pip command can be used for this:

pip install igraph
pip install igraph
SHELL

Creating a Graph Using Igraph

Here's a simple example to show you how to use igraph to construct and set up a graph:

from igraph import Graph, plot

# Create an empty graph
g = Graph()

# Add vertices (nodes)
g.add_vertices(5) # Adding 5 vertices

# Add edges (connections between vertices)
g.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2)]) # Adding edges

# Add vertex ids and edge attributes
g.vs["name"] = ["A", "B", "C", "D", "E"] # Vertex labels
g.es["weight"] = [1, 2, 3, 4, 5, 6] # Edge weights

# Print basic graph structural properties
print("Number of vertices:", g.vcount())
print("Number of edges:", g.ecount())
print("Graph summary:", g.summary())
from igraph import Graph, plot

# Create an empty graph
g = Graph()

# Add vertices (nodes)
g.add_vertices(5) # Adding 5 vertices

# Add edges (connections between vertices)
g.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2)]) # Adding edges

# Add vertex ids and edge attributes
g.vs["name"] = ["A", "B", "C", "D", "E"] # Vertex labels
g.es["weight"] = [1, 2, 3, 4, 5, 6] # Edge weights

# Print basic graph structural properties
print("Number of vertices:", g.vcount())
print("Number of edges:", g.ecount())
print("Graph summary:", g.summary())
PYTHON

Console Output

πŸ‘ igraph python (How it Works for Developers): Figure 2 - Console output from the code example

Configure Graph Layout and Visualization

We can draw the graph using some of igraph's inbuilt features. Change the appearance and layout with the following:

# Define a layout for the graph
layout = g.layout("circle") # Layout in a circular arrangement

# Plot the graph with labels and custom options
plot(
 g,
 layout=layout,
 vertex_label=g.vs["name"], # Label vertices
 vertex_color="lightblue", # Vertex color
 edge_width=g.es["weight"], # Edge width based on weight
 vertex_size=30, # Vertex size
 edge_color="grey", # Edge color
 bbox=(300, 300), # Size of the plot
 margin=20 # Margin around the plot
)

# Save the plotted graph to a file
plot(g, layout=layout, bbox=(300, 300), margin=20).save('exampleGraph.png') 
# Define a layout for the graph
layout = g.layout("circle") # Layout in a circular arrangement

# Plot the graph with labels and custom options
plot(
 g,
 layout=layout,
 vertex_label=g.vs["name"], # Label vertices
 vertex_color="lightblue", # Vertex color
 edge_width=g.es["weight"], # Edge width based on weight
 vertex_size=30, # Vertex size
 edge_color="grey", # Edge color
 bbox=(300, 300), # Size of the plot
 margin=20 # Margin around the plot
)

# Save the plotted graph to a file
plot(g, layout=layout, bbox=(300, 300), margin=20).save('exampleGraph.png') 
PYTHON

Outputted Graph

Below is the simple graph image that has been generated with the help of the Matplotlib library and the Python bindings of the Cairo library.

πŸ‘ igraph python (How it Works for Developers): Figure 3 - Outputted graph

Advanced Graph Operations

Perform various graph operations and analyses, such as calculating centrality, finding communities, or identifying shortest paths:

# Calculate degree centrality for each vertex
degrees = g.degree()
print("Degrees of vertices:", degrees)

# Compute shortest path between two vertices that don't have a predefined distance
shortest_path = g.shortest_paths_dijkstra(source=0, target=3)
print("Shortest path from vertex 0 to 3:", shortest_path)

# Detect communities using the Louvain method
communities = g.community_multilevel()
print("Detected communities:", communities)
# Calculate degree centrality for each vertex
degrees = g.degree()
print("Degrees of vertices:", degrees)

# Compute shortest path between two vertices that don't have a predefined distance
shortest_path = g.shortest_paths_dijkstra(source=0, target=3)
print("Shortest path from vertex 0 to 3:", shortest_path)

# Detect communities using the Louvain method
communities = g.community_multilevel()
print("Detected communities:", communities)
PYTHON

Console Outputs

πŸ‘ igraph python (How it Works for Developers): Figure 4 - Console output from the previous calculations

Introducing IronPDF

πŸ‘ igraph python (How it Works for Developers): Figure 5 - IronPDF webpage

We can even generate and edit PDFs programmatically using the IronPDF Python module. Using this library, you will have an enormous capability to create PDF documents from HTML, merge two or more PDF documents, and even make use of existing PDFs and modify them to include text, photos, and annotations. IronPDF enables you to generate professional-quality PDFs from any HTML site or Web content suitable for generating reports, invoices, and other documents that have preset styles.

Some of its advanced features include editing page layouts, document encryption, and text extraction from a PDF. It will help developers be better positioned to improve the general usefulness of your products if they can handle PDFs better.

Installing the IronPDF Library

You can use the following command to install the packages that allow the Python interface to enable IronPDF capabilities for your project:

 pip install ironpdf

Integrating igraph with IronPDF

These are the steps you would take in Python to merge igraph and IronPDF: First, you will create a graph with igraph and display it. Then, turn the resulting visualization into a PDF.

from igraph import Graph, plot
import matplotlib.pyplot as plt
from ironpdf import ImageToPdfConverter, License
import warnings

# Suppress warnings for cleaner output
warnings.filterwarnings('ignore')

# Ensure that you have replaced the string with your own license key
License.LicenseKey = "YOUR LICENSE KEY GOES HERE"

# Create an empty graph
g = Graph()

# Add adjacent vertices (nodes)
g.add_vertices(5) # Adding 5 vertices

# Add edges (connections between vertices)
g.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2)]) # Adding edges

# Add vertex and edge attributes
g.vs["name"] = ["A", "B", "C", "D", "E"] # Vertex labels
g.es["weight"] = [1, 2, 3, 4, 5, 6] # Edge weights

# Define a layout for the graph
layout = g.layout("circle") # Layout in a circular arrangement

# Create a plot using matplotlib
fig, ax = plt.subplots()

# Plot the graph with specified layout and styles
plot(
 g,
 target=ax,
 layout=layout,
 vertex_label=g.vs["name"], # Label vertices
 vertex_color="lightblue", # Vertex color
 edge_width=g.es["weight"], # Edge width based on weight
 vertex_size=30, # Vertex size
 edge_color="grey", # Edge color
 bbox=(300, 300), # Size of the plot
 margin=20 # Margin around the plot
)

# Save the plot as a PNG image
plt.savefig('result.png')

# Convert the image to a PDF file
ImageToPdfConverter.ImageToPdf('result.png').SaveAs("result.pdf")
from igraph import Graph, plot
import matplotlib.pyplot as plt
from ironpdf import ImageToPdfConverter, License
import warnings

# Suppress warnings for cleaner output
warnings.filterwarnings('ignore')

# Ensure that you have replaced the string with your own license key
License.LicenseKey = "YOUR LICENSE KEY GOES HERE"

# Create an empty graph
g = Graph()

# Add adjacent vertices (nodes)
g.add_vertices(5) # Adding 5 vertices

# Add edges (connections between vertices)
g.add_edges([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2)]) # Adding edges

# Add vertex and edge attributes
g.vs["name"] = ["A", "B", "C", "D", "E"] # Vertex labels
g.es["weight"] = [1, 2, 3, 4, 5, 6] # Edge weights

# Define a layout for the graph
layout = g.layout("circle") # Layout in a circular arrangement

# Create a plot using matplotlib
fig, ax = plt.subplots()

# Plot the graph with specified layout and styles
plot(
 g,
 target=ax,
 layout=layout,
 vertex_label=g.vs["name"], # Label vertices
 vertex_color="lightblue", # Vertex color
 edge_width=g.es["weight"], # Edge width based on weight
 vertex_size=30, # Vertex size
 edge_color="grey", # Edge color
 bbox=(300, 300), # Size of the plot
 margin=20 # Margin around the plot
)

# Save the plot as a PNG image
plt.savefig('result.png')

# Convert the image to a PDF file
ImageToPdfConverter.ImageToPdf('result.png').SaveAs("result.pdf")
PYTHON

This script will generate a graph through igraph, visualize it with matplotlib, and then use IronPDF to turn the chart into a PDF. This code will import all necessary libraries and set up IronPDF with a license key. Create an empty graph with five vertices and six edges and add weights and labels for clarity.

The graph is laid out circularly, and the plotting involves matplotlib with several visualization properties, such as vertex color and size, and edge line widths. After that, the resultβ€”as an image file, result.png, is saved. Finally, it is transformed into a PDF, result.pdf, with IronPDF's ImageToPdfConverter. Graph creation, visualization, and PDF production are combined into one workflow.

Outputted PDF

πŸ‘ igraph python (How it Works for Developers): Figure 6 - Outputted PDF

Licensing

A licensing key is needed to allow the code to work without a watermark. You can register for a free trial license at this link. Note that you can register for one without providing proof of identity. All you need to do to register for the free trial version is to input your email address.

πŸ‘ igraph python (How it Works for Developers): Figure 7 - IronPDF licensing plan

Conclusion

With the power of IronPDF and igraph, you can develop solutions for visualizing and presenting complex graph data. Through igraph, you can easily create and analyze complex networks, while using IronPDF for the seamless conversion of data visualizations into professional-grade PDF documents. These combined forces will help you develop comprehensive reports, including both graph analyses and visual representations.

This integration enables the development of various applications that demand comprehensive network documentation, including academic research, business analytics, and data-driven reporting. Furthermore, it combines high-quality document output with very powerful manipulation capabilities with graphs. On top of all that, Iron Software provides a multiplicity of libraries, making it easier to develop applications for a range of platforms and operating systems like Windows, Android, MAC, Linux, and others.

Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More

Related Articles

Updated

imageio python (How it Works for Developers)

we will look into how Imageio can be used to read and write images, later we will also look into IronPDF from Iron Software to generate PDF documents

Read More

Install with pip
Version: 2026.6
 pip install ironpdf
  1. Download and install Python 3.7+.
  2. Install pip from pypi.org if it isn't installed already.
  3. Execute the above command in the terminal.
Download Module
Version: 2026.6
Download Now
Manually install into your project
  1. Download the package
  2. Run this command from the terminal
    pip install ironpdf-2026.6-py37-none-win_amd64.whi
Licenses from $749

Have a question? Get in touch with our development team.

Now you've installed with PyPi
Your browser is now downloading IronPDF

Next step: Start free 30-day Trial

No credit card required

  • Test in a live environment
  • Fully-functional product
  • 24/5 technical support

Thank You

Your trial key should be in the email.
If it is not, please contact
support@ironsoftware.com
Get your free 30-day Trial Key instantly.
Thank you.
If you'd like to speak to our licensing team:
πŸ‘ badge_greencheck_in_yellowcircle
The trial form was submitted
successfully.

Your trial key should be in the email.
If it is not, please contact
support@ironsoftware.com

Have a question? Get in touch with our development team.
No credit card or account creation required
Now you've installed with PyPi
Your browser is now downloading IronPDF

Next step: Start free 30-day Trial

No credit card required

  • Test in a live environment
  • Fully-functional product
  • 24/5 technical support
Thank you.
View your license options:
Thank you.
If you'd like to speak to our licensing team:
Have a question? Get in touch with our development team.
Have a question? Get in touch with our development team.
Talk to Sales Team

Book a No-obligation Consult

How we can help:
  • Consult on your workflow & pain points
  • See how other companies solve their .NET document needs
  • All your questions answered to make sure you have all the information you need. (No commitment whatsoever.)
  • Get a tailored quote for your project's needs
Get Your No-Obligation Consult

Complete the form below or email sales@ironsoftware.com

Your details will always be kept confidential.

Trusted by Millions of Engineers Worldwide
Book Free Live Demo

Book a 30-minute, personal demo.

No contract, no card details, no commitments.

Here's what to expect:
  • A live demo of our product and its key features
  • Get project specific feature recommendations
  • All your questions are answered to make sure you have all the information you need.
    (No commitment whatsoever.)
CHOOSE TIME
YOUR INFO
Book your free Live Demo

Trusted by Millions of Engineers Worldwide

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me