0
0
Matplotlibdata~5 mins

Custom colormaps in Matplotlib

Choose your learning style9 modes available
Introduction

Custom colormaps help you choose colors that make your data easier to understand and look nicer.

You want to highlight specific ranges of values in a heatmap.
You need colors that match your company or project style.
Default colors are hard to see or confusing for your data.
You want to create a smooth color transition for your plot.
You want to emphasize differences in data clearly.
Syntax
Matplotlib
from matplotlib.colors import LinearSegmentedColormap

custom_cmap = LinearSegmentedColormap.from_list('name', ['color1', 'color2', ...], N=256)

You create a colormap by giving a list of colors that blend smoothly.

The N parameter sets how many colors the map has (default is 256).

Examples
This creates a colormap that goes from blue to red smoothly.
Matplotlib
from matplotlib.colors import LinearSegmentedColormap

# Simple two-color map from blue to red
custom_cmap = LinearSegmentedColormap.from_list('blue_red', ['blue', 'red'])
This colormap transitions from green to yellow to red.
Matplotlib
from matplotlib.colors import LinearSegmentedColormap

# Three colors: green, yellow, and red
custom_cmap = LinearSegmentedColormap.from_list('green_yellow_red', ['green', 'yellow', 'red'])
This creates a black-to-white colormap with 100 color steps.
Matplotlib
from matplotlib.colors import LinearSegmentedColormap

# Custom number of colors (100)
custom_cmap = LinearSegmentedColormap.from_list('custom', ['black', 'white'], N=100)
Sample Program

This program creates a heatmap of a sine function using a custom colormap that blends blue, white, and red colors.

Matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

# Create sample data
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X**2 + Y**2)

# Define a custom colormap from blue to white to red
colors = ['blue', 'white', 'red']
custom_cmap = LinearSegmentedColormap.from_list('blue_white_red', colors)

# Plot the data with the custom colormap
plt.imshow(Z, cmap=custom_cmap)
plt.colorbar()
plt.title('Heatmap with Custom Colormap')
plt.show()
OutputSuccess
Important Notes

You can use color names or hex color codes like '#FF0000' for red.

Custom colormaps help make your plots clearer and more attractive.

Try different color combinations to see what works best for your data.

Summary

Custom colormaps let you control how colors show your data.

Use LinearSegmentedColormap.from_list with a list of colors.

Custom colors improve understanding and style of your plots.