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
Selected Reading
How to plot data into imshow() with custom colormap in Matplotlib?
To plot data into imshow() with custom colormap in Matplotlib, we can create our own colormap from a list of colors and apply it to display 2D data as an image.
Creating a Custom Colormap
We use ListedColormap to generate a colormap object from a list of colors ?
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create random data
data = np.random.rand(5, 5)
# Create custom colormap from colors
cmap = ListedColormap(['red', 'green', 'blue'])
# Display data with custom colormap
plt.imshow(data, cmap=cmap)
plt.colorbar()
plt.title('Custom Colormap Example')
plt.show()
Advanced Custom Colormap
You can create more sophisticated colormaps using hex colors or RGB tuples ?
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
# Create sample data
data = np.random.rand(8, 8)
# Custom colormap with hex colors
colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF']
custom_cmap = ListedColormap(colors)
plt.figure(figsize=(10, 4))
# Plot 1: Basic colormap
plt.subplot(1, 2, 1)
plt.imshow(data, cmap='viridis')
plt.title('Default Viridis Colormap')
plt.colorbar()
# Plot 2: Custom colormap
plt.subplot(1, 2, 2)
plt.imshow(data, cmap=custom_cmap)
plt.title('Custom Colormap')
plt.colorbar()
plt.tight_layout()
plt.show()
Colormap with Specific Value Ranges
You can control how values map to colors using vmin and vmax parameters ?
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
# Create structured data
data = np.array([[1, 2, 3, 4],
[2, 3, 4, 1],
[3, 4, 1, 2],
[4, 1, 2, 3]])
# Custom colormap for discrete values
colors = ['lightblue', 'yellow', 'orange', 'red']
discrete_cmap = ListedColormap(colors)
plt.imshow(data, cmap=discrete_cmap, vmin=1, vmax=4)
plt.colorbar(label='Value')
plt.title('Discrete Custom Colormap')
# Add text annotations
for i in range(4):
for j in range(4):
plt.text(j, i, str(data[i, j]), ha='center', va='center',
color='black', fontsize=12, fontweight='bold')
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
cmap |
Colormap object or name | ListedColormap(['red', 'blue']) |
vmin |
Minimum data value for colormap | vmin=0 |
vmax |
Maximum data value for colormap | vmax=1 |
Conclusion
Use ListedColormap to create custom colormaps from color lists. Combine with imshow() to visualize 2D data with personalized color schemes that enhance data interpretation.
Advertisements
