Python - Visualize graphs generated in NetworkX using Matplotlib


Introduction

Python represents a flexible coding language recognized for its ease and clearness. This offers many libraries and components for streamlining different tasks, including the creation of graphs and displays. NetworkX represents an efficient Python toolkit for constructing, changing, and investigating the arrangement, movement, and operations of sophisticated networks. Matplotlib, however, is a popular toolkit for creating static, animated, and interactive visualizations in Python.

Definition

NetworkX serves as a Python library for building, modifying, and investigating the arrangement, movement, and capabilities of elaborate networks. This offers multiple features and mathematical formulas to produce a variety of graphical representations. This includes oriented and unoriented networks, multidigraphs, and two−part diagrams.

Matplotlib provides extensive functionality to generate static, dynamic, and interactive plots with Python. This provides numerous for visualizing data, such as line plots, scatter plots, bar plots, histograms, and more.

Syntax

import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge(1, 2)
G.add_edge(2, 3)
nx.draw(G)
plt.show()
plt.savefig("filename.png")        

The initial stage of the program entails importing the essential modules, `networkx` and `matplotlib.pyplot`. Then, a blank graph variable `G` gets created using the `Graph()` subroutine within the `networkx` library.

To define the layout of the diagram, two connecting lines are placed through the `add_edge()` function.

Once the definition is complete the structure of the graph is, the program continues to visualize the graph employing the `draw()` function from the `networkx` framework. The `draw()` method receives the graph `G` as a variable and generates a visual output of the network. As a default, the function `draw()` employs a spring placement algorithm to place the elements. It shows the plot with preset visual features.

The'show()' function call from the library'matplotlib.pyplot' is used to display the constructed plot. According to the conditions where the script is run.

Ultimately, the program stores the chart as a picture file called "filename.png". It employs the `savefig()` procedure from the `matplotlib.pyplot` framework. This function enables the user to define a file name and format (like PNG, JPEG, PDF) to store the plot. In this scenario, the chart is preserved as a picture in PNG format having the title "filetitle.png". The document is going to be saved within the identical folder just like the Python script or notebook.

Algorithm

  • Step 1: Import the required libraries: networkx and matplotlib.pyplot.

  • Step 2: Generate a graph using NetworkX.

  • Step 3: Draw the graph using Matplotlib.

  • Step 4: Save the drawing of the graph in a file.

  • Step 5: Display the drawing of the graph.

Approach

  • Approach 1: Visualizing Graphs with Node Labels and Edge Weights

  • Approach 2: Visualizing Large Graphs with Subplots

Approach 1: Visualizing Graphs with Node Labels and Edge Weights

Example

import networkx as nx
import matplotlib.pyplot as plt

# Create graph
G = nx.Graph()

# Add nodes
G.add_node(1, label='A')
G.add_node(2, label='B')
G.add_node(3, label='C')
G.add_node(4, label='D')

# Add edges
G.add_edge(1, 2, weight=4)
G.add_edge(2, 3, weight=7)
G.add_edge(3, 1, weight=2)
G.add_edge(1, 4, weight=5)

# Set node positions
pos = nx.spring_layout(G)

# Draw nodes and labels
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos, labels=nx.get_node_attributes(G, 'label'))

# Draw edges with weights
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
nx.draw_networkx_edges(G, pos)

# Show graph
plt.axis('off')
plt.show()

Output

We create an empty graph object called G using the Graph() function from NetworkX.

It's now time to populate our graph with nodes. To add individual nodes to the graph, we utilise the add_node() function. Each node is given a unique identity, and we can also give the nodes labels by utilising a custom property. We label node 1 as 'A,' node 2 as 'B,' node 3 as 'C,' and node 4 as 'D' in this example.

We'll develop edges to connect the nodes when we've added them. To add edges between nodes, we utilise the add_edge() function. For example, node 1 and 2 are connected by a four−weighted edge.

To see the graph, we must first position the nodes. To automatically compute the placements of the nodes, we use NetworkX's spring_layout() method. This function applies an algorithm that tries to arrange the nodes in an aesthetically pleasing manner.

Now comes the exciting part – visualizing the graph! We use various NetworkX functions and Matplotlib to create the plot. We start by drawing the nodes using draw_networkx_nodes() and the labels using draw_networkx_labels(). We pass in the graph object G and the positions pos that we calculated earlier. This ensures that the nodes and labels are displayed in the correct positions.

To visualize the edges, we also draw them using the draw_networkx_edges() function. Additionally, we include the edge weights by using the draw_networkx_edge_labels() function. This function adds the edge weights as labels near the corresponding edges.

Finally, we display the graph plot using plt.show(). This will open a window or display the plot in the Jupyter Notebook interface. To make the plot look more clean and focused on the graph itself, we use plt.axis('off') to turn off the axes' visibility.

Approach 2: Visualizing Large Graphs with Subplots

Example

import networkx as nx
import matplotlib.pyplot as plt

# Create graph
G = nx.path_graph(5)

# Create subplots
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(10, 5))

# Plot original graph
axs[0].set_title('Original Graph')
nx.draw(G, ax=axs[0])

# Plot modified graph
axs[1].set_title('Modified Graph')
pos = nx.spring_layout(G)
nx.draw(G, pos=pos, ax=axs[1], node_color='r', node_size=500, with_labels=False)
plt.suptitle('Visualization of Large Graph with Subplots')
plt.show()

Output

First, we import the necessary libraries: NetworkX and Matplotlib.pyplot. These libraries provide us with functions and tools to create and visualize graphs.

Next, we create a graph object called G using the path_graph() function from NetworkX. This function generates a simple path graph with 5 nodes connected in a linear manner.

To organise the visualisations, we use Matplotlib's subplots() method to construct subplots. We indicate the number of subplot rows and columns (in this case, one row and two columns), as well as the figure size.

This helps us divide the plot area into multiple sections to display different graphs.

Now, it's time to plot the original graph on the first subplot. We access the first subplot using the index 0, and set its title using the set_title() function. Then, we use the draw() function from NetworkX to visualize the original graph on this subplot.

Moving on to the second subplot, we repeat the process. We set its title and access it using the index 1. We also calculate the node positions using the spring_layout() function from NetworkX, which arranges the nodes in an aesthetically pleasing manner. Then, we use the draw() function again to visualize the modified graph on this subplot. Here, we can customize the node color, size, and labels to differentiate it from the original graph.

To enhance the overall presentation, we add a common title to the entire figure using the suptitle() function from Matplotlib.

Conclusion

By this we got to know about these topics correctly. We've successfully created a graph, set up subplots, and visualized the graph using NetworkX and Matplotlib.

Updated on: 27-Jul-2023

664 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements