Thursday, December 19, 2024

How to create a customized colormaps in Matplotlib?

Besides specifying named colors, hexadecimal colors, RGB and RGBA, and colormaps, the matplotlib offers the ability of defining your own colormap.This can be done us by combining the existing ones or by specifying the list of colors.
To create the custom colormap with specific colors at certain points along the color scale, and creating the smooth gradient between those certain points the LinearSegmentedColormap from matplotlib color module is used. When you specify the color list and apply the Linear Segemented Colors class will interpolate the colors in between, giving you the precise control over the appearance of the colormap. It is a very useful tool for creating unique color schemes tailored to your data visualizaton needs. To import the Linear SegementedColormap write the following code.
from matplotlib.colors import LinearSegmentedColormap
To show the example of how LinearSegmentColormap works we will need to plot some data. For data generation we will need the numpy library and for plotting this data we will use the maptlotlib.pyplot function.
import numpy as  np
import matplotlib.pyplot asplt
The data will be numpy matrix 10x10 with random vlaues from 0 to 1. To test this LinearSegmentedColormap class we will create a simple list containin three colors i.e. blue, green, and red.
colors = ['blue'. 'green', 'red']
The next step is to create a custom colormap and to do that LinearSegmentedColormap.from_list is needed The arguments in this function will be the name of the color list (string) which will be called ”my cmap”, and we also have to provide the list of colors. The newly created colormap will be stored under the custom_cmap variable.
custom_cmap = LinearSegmentedColormap.from_list("my_cmap", colors)
Now we will show the data in form of the heatmap using the plt.imshow() funciton.
plt.imshow(data, cmap = custom_cmap)
The entire code is shwon below and the imshow plot is shown in Figure 1.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
colors = ['blue', 'green', 'red']
custom_cmap = LinearSegmentedColormap.from_list("my_cmap", colors)
data = np.random.rand(10,10)
plt.imshow(data,cmap =custom_cmap)
2024-12-19T23:25:00.103456 image/svg+xml Matplotlib v3.8.0, https://matplotlib.org/
Figure 1 - The ishow plot with custom colormap

No comments:

Post a Comment