Create a Custom Colormap and Color Scale in Matplotlib
Problem:
Design a custom colormap that transitions smoothly from red to violet to blue, mapping to values between -2 and 2. Utilize the colormap to color points in a plot and display the associated color scale.
Implementation:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors
# Generate random data
x, y, c = zip(*np.random.rand(30, 3) * 4 - 2)
# Create a custom colormap
colors = ["red", "violet", "blue"]
norm = plt.Normalize(-2, 2)
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", colors)
# Plot using custom colormap
plt.scatter(x, y, c=c, cmap=cmap, norm=norm)
# Add color scale
plt.colorbar()
plt.show()
Explanation:
-
LinearSegmentedColormap: Instead of a ListedColormap that produces discrete colors, we use a LinearSegmentedColormap to create a continuous gradient.
-
Normalization: The Normalize function maps the data values into a range between 0 and 1, ensuring that the colors are appropriately distributed.
-
RGBA Specification: The colors are specified as strings of the desired color names.
-
Scatter Plot: The data points are plotted using the custom colormap, and each point is assigned a color based on its corresponding data value.
-
Color Scale: The colorbar displays the color gradient and the mapped values, enabling the user to visualize the color-value relationship.
Additional Considerations:
-
Multiple Values: To create a colormap that maps more than three values to colors, specify additional tuples of normalized values and colors in the from_list method.
-
Colorbar Ticks: Adjust the colorbar ticks using the set_ticks method to customize the displayed values.
The above is the detailed content of How to Create a Custom Colormap and Color Scale in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!
Statement: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