Everything you need to know about Graphs.

Aditi Deodhar
4 min readFeb 11, 2024

--

Embarking on a Graphical Adventure: A Beginner’s Guide to Graph Data Structure with Python

Photo by GuerrillaBuzz on Unsplash

Welcome aboard, aspiring adventurers! Today, we’re setting sail on a thrilling journey into the world of graph data structures. Graphs, those intricate webs of connections and relationships, are the backbone of modern-day technology, powering everything from social networks to navigation systems. And with Python as our trusty compass, we’re poised to navigate this exciting terrain with ease. So, buckle up, hold on tight, and get ready to embark on a graphical adventure like no other!

Unraveling the Mysteries of Graphs:

Before we dive headfirst into the deep end, let’s take a moment to understand what graphs are all about.

At its simplest, a graph is a collection of nodes (vertices) connected by edges (lines). These connections represent relationships between the nodes, whether it’s friendships between individuals, roads between cities, or dependencies between tasks. Think of graphs as maps of connectivity, guiding us through the intricate landscapes of our digital world.

Types of Graphs:

Like characters in a grand epic, graphs come in many shapes and sizes, each with its own unique traits and attributes. Here are a few common types you’re likely to encounter:

  1. Directed Graphs (Digraphs): Think of these as one-way streets, where edges have a direction, indicating a flow from one node to another.
  2. Undirected Graphs: In these graphs, edges have no direction, symbolizing a two-way relationship between nodes, much like a friendship between two people.
  3. Weighted Graphs: These graphs assign a weight or value to each edge, representing factors such as distance, cost, or importance.
  4. Cyclic and Acyclic Graphs: Cyclic graphs contain cycles, or loops, where you can traverse a series of edges and return to the starting node. Acyclic graphs, as the name suggests, have no cycles, offering a more straightforward structure.

Practical Applications:
Now that we’ve got the lay of the land, let’s explore some practical applications of graphs in the real world:

  1. Social Networks: Graphs power social media platforms, allowing us to visualize connections between users, communities, and interests.
  2. Route Planning: Navigation systems rely on graphs to calculate the shortest and fastest routes between locations, taking into account factors like traffic and road conditions.
  3. Recommendation Systems: Graphs help recommend products, movies, or music based on similar interests or preferences, creating personalized experiences for users.
  4. Network Analysis: From detecting fraud in financial transactions to identifying influential nodes in a communication network, graphs offer valuable insights into complex systems.

Hands-On with Python:

Now comes the fun part — getting our hands dirty with Python!

We’ll be using the NetworkX library, a powerful tool for creating, manipulating, and visualizing graphs.

If you haven’t already installed NetworkX, you can do so using pip:

pip install networkx

Let’s kick things off with a simple example.

Open up your favorite Python editor and follow along as we create our very own graph:

import networkx as nx
import matplotlib.pyplot as plt

# Create an empty graph
G = nx.Graph()

# Add nodes (vertices)
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_node("D")

# Add edges (connections)
G.add_edge("A", "B")
G.add_edge("B", "C")
G.add_edge("C", "D")
G.add_edge("D", "A")

# Visualize the graph
nx.draw(G, with_labels=True)
plt.show()

Manipulating graphs involves performing various operations such as adding or removing nodes and edges, accessing properties of nodes and edges, and analyzing the structure of the graph.

# Remove a node
G.remove_node("C")
# Remove an edge
G.remove_edge("C", "D")

# Add attributes to nodes
G.nodes["A"]['color'] = 'red'
G.nodes["B"]['size'] = 10

# Access node attributes
print(G.nodes["A"]['color']) # Output: 'red'

# Add attributes to edges
G.edges[("A", "B")]['weight'] = 5.0

# Access edge attributes
print(G.edges[("A", "B")]['weight']) # Output: 5.0

NetworkX provides various methods for analyzing the structure of a graph, such as determining the number of nodes and edges, calculating the degree of nodes, and checking for connectivity.

# Number of nodes and edges
print(“Number of nodes:”, G.number_of_nodes())
print(“Number of edges:”, G.number_of_edges())

# Degree of nodes
print("Degree of node 1:", G.degree(1))

# Check for connectivity
print("Is the graph connected?", nx.is_connected(G))

These are just a few examples of graph manipulation operations in Python using the NetworkX library. With these tools at your disposal, you can manipulate and analyze graphs to suit your specific needs and applications.

Congratulations, fellow adventurers! You’ve taken your first steps into the enchanting world of graph data structures with Python. Armed with your newfound knowledge, the possibilities are endless. So go forth, explore, and may your journeys be filled with discovery and wonder.

Until next time, happy graphing! 📈

--

--

Aditi Deodhar

MSIS @ Northeastern University | Data Science Enthusiast