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 plot a 2D matrix in Python with colorbar Matplotlib?
To plot a 2D matrix in Python with a colorbar, we can use NumPy to create a 2D array matrix and use that matrix in the imshow() method along with matplotlib's colorbar functionality.
Steps
Create a 2D data matrix using NumPy
Use
imshow()method to display data as an image on a 2D regular rasterCreate a colorbar for the ScalarMappable instance using
colorbar()methodDisplay the figure using
show()method
Basic Example with Random Data
Here's how to create a simple 2D matrix plot with a colorbar ?
import numpy as np import matplotlib.pyplot as plt # Set figure size for better visualization plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True # Create a 2D matrix with random data data2D = np.random.random((50, 50)) # Plot the matrix and store the image object im = plt.imshow(data2D, cmap="copper_r") # Add colorbar plt.colorbar(im) # Display the plot plt.show()
Example with Custom Data
You can also create a matrix with structured data for better visualization ?
import numpy as np
import matplotlib.pyplot as plt
# Create a custom 2D matrix
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
# Create a function for visualization (e.g., Gaussian)
Z = np.exp(-(X**2 + Y**2))
# Plot with different colormap
plt.figure(figsize=(8, 6))
im = plt.imshow(Z, cmap='viridis', extent=[-3, 3, -3, 3])
plt.colorbar(im, label='Intensity')
plt.title('2D Gaussian Distribution')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Customizing the Colorbar
You can customize the colorbar appearance and add labels ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
data = np.random.randn(30, 30)
# Create the plot
fig, ax = plt.subplots(figsize=(8, 6))
im = ax.imshow(data, cmap='plasma')
# Customize colorbar
cbar = plt.colorbar(im, ax=ax, shrink=0.8)
cbar.set_label('Values', rotation=270, labelpad=15)
# Add title and labels
ax.set_title('2D Matrix Plot with Custom Colorbar')
ax.set_xlabel('Column Index')
ax.set_ylabel('Row Index')
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Example Values |
|---|---|---|
cmap |
Colormap for visualization | 'viridis', 'plasma', 'copper_r' |
extent |
Define axis limits | [xmin, xmax, ymin, ymax] |
shrink |
Colorbar size scaling | 0.5 to 1.0 |
label |
Colorbar label text | 'Intensity', 'Temperature' |
Conclusion
Use imshow() with colorbar() to visualize 2D matrices effectively. Choose appropriate colormaps and customize the colorbar labels for better data interpretation.
