Home > Backend Development > Python Tutorial > How to Create a Custom Colormap and Add a Color Scale in Matplotlib?

How to Create a Custom Colormap and Add a Color Scale in Matplotlib?

Susan Sarandon
Release: 2024-11-13 05:24:02
Original
499 people have browsed it

How to Create a Custom Colormap and Add a Color Scale in Matplotlib?

Creating a Custom Colormap and Incorporating a Color Scale

To create your own colormap, one approach is to utilize the LinearSegmentedColormap function from the matplotlib.colors module. This approach is simpler and produces a continuous color scale.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

# Generate random data points
x, y, c = zip(*np.random.rand(30, 3) * 4 - 2)

# Define lower and upper bounds for normalization
norm = plt.Normalize(-2, 2)

# Create a list of tuples representing the values and corresponding colors
tuples = [(norm(-2.), 'red'), (norm(-1.), 'violet'), (norm(2.), 'blue')]

# Generate the colormap from the list of tuples
cmap = matplotlib.colors.LinearSegmentedColormap.from_list('', tuples)

# Plot the data points using the custom colormap
plt.scatter(x, y, c=c, cmap=cmap, norm=norm)

# Add a color scale to the plot
plt.colorbar()
plt.show()
Copy after login

This code snippet successfully creates a colormap with a smooth transition from red to violet to blue, ranging from -2 to 2. The color scale is also incorporated to the right of the plot, allowing for easy color interpretation.

The above is the detailed content of How to Create a Custom Colormap and Add a Color Scale in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template