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 draw node colormap in NetworkX/Matplotlib?
To draw a node colormap in NetworkX with Matplotlib, you can assign different colors to nodes based on numerical values and specify a colormap. This creates visually appealing graphs where node colors represent data values.
Steps to Create Node Colormap
- Set the figure size and adjust the padding between and around the subplots
- Create a graph structure (cycle graph with cyclically connected nodes)
- Position the nodes using a layout algorithm
- Draw the graph with node colors mapped to a colormap
- Display the figure using
show()method
Basic Example
Here's how to create a circular graph with nodes colored using a colormap −
import matplotlib.pyplot as plt import networkx as nx plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create a cycle graph with 24 nodes G = nx.cycle_graph(24) # Position nodes in a circle pos = nx.circular_layout(G) # Draw with node colormap nx.draw(G, pos, node_color=range(24), node_size=800, cmap='copper') plt.show()
Advanced Example with Custom Colors
You can also use custom color values and different colormaps −
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
# Create a random graph
G = nx.erdos_renyi_graph(15, 0.3)
# Generate random color values for nodes
node_colors = np.random.rand(len(G.nodes()))
# Position nodes using spring layout
pos = nx.spring_layout(G, seed=42)
# Draw with viridis colormap
nx.draw(G, pos,
node_color=node_colors,
node_size=600,
cmap='viridis',
with_labels=True)
plt.colorbar(plt.cm.ScalarMappable(cmap='viridis'))
plt.title("NetworkX Graph with Node Colormap")
plt.show()
Key Parameters
| Parameter | Description | Example Values |
|---|---|---|
node_color |
Color values for nodes | List, array, or range |
cmap |
Colormap name | 'viridis', 'copper', 'plasma' |
node_size |
Size of nodes | 300, 600, 800 |
Output
The code generates a circular graph where each node is colored according to its position in the sequence, creating a gradient effect using the copper colormap.
Conclusion
Using node_color with a cmap parameter allows you to create visually informative graphs where node colors represent data values. This technique is particularly useful for visualizing network properties or clustering results.
