Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to make multipartite graphs using networkx and Matplotlib?
A multipartite graph is a graph where nodes are divided into multiple disjoint sets, with edges only connecting nodes from different sets. NetworkX provides tools to create and visualize these structures using multipartite_layout() for positioning nodes in distinct layers.
Steps to Create a Multipartite Graph
Set the figure size and adjust the padding between and around the subplots
Create a list of subset sizes and colors for each layer
Define a method for multilayered graph that returns a graph object
Assign colors to nodes based on their layers
Position the nodes in layers using
multipartite_layout()Draw the graph with Matplotlib
Display the figure using
show()method
Example
Here's how to create a multipartite graph with 8 layers of varying sizes ?
import itertools
import matplotlib.pyplot as plt
import networkx as nx
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
subset_sizes = [5, 5, 4, 3, 2, 4, 4, 3]
subset_color = [
"gold",
"violet",
"violet",
"violet",
"violet",
"limegreen",
"limegreen",
"darkorange",
]
def multilayered_graph(*subset_sizes):
extents = nx.utils.pairwise(itertools.accumulate((0,) + subset_sizes))
layers = [range(start, end) for start, end in extents]
G = nx.Graph()
for (i, layer) in enumerate(layers):
G.add_nodes_from(layer, layer=i)
for layer1, layer2 in nx.utils.pairwise(layers):
G.add_edges_from(itertools.product(layer1, layer2))
return G
G = multilayered_graph(*subset_sizes)
color = [subset_color[data["layer"]] for v, data in G.nodes(data=True)]
pos = nx.multipartite_layout(G, subset_key="layer")
nx.draw(G, pos, node_color=color, with_labels=False)
plt.axis("equal")
plt.show()
Output
How It Works
The multilayered_graph() function creates nodes in sequential ranges for each layer and connects every node in one layer to every node in adjacent layers. The multipartite_layout() arranges nodes vertically by their layer attribute, creating the characteristic layered appearance.
Key Components
subset_sizes − Defines number of nodes in each layer
subset_color − Assigns colors to distinguish layers
layer attribute − Tags each node with its layer number
itertools.product() − Creates edges between all nodes in adjacent layers
Conclusion
Multipartite graphs are useful for modeling relationships between distinct groups. Use multipartite_layout() to position nodes in layers and assign colors to distinguish different partitions visually.
