Home > Article > Backend Development > How to Create Custom Colormaps and Color Scales with Matplotlib?
Creating Custom Colormaps and Color Scales with Matplotlib:
Creating a custom colormap in matplotlib involves a straightforward process. To establish a continuous (smooth) color scale, consider leveraging the LinearSegmentedColormap instead of the ListedColormap.
import numpy as np import matplotlib.pyplot as plt import matplotlib.colors # Defining random data points x, y, c = zip(*np.random.rand(30, 3)*4 - 2) # Establishing normalization parameters norm = plt.Normalize(-2, 2) # Generating a linear segmented colormap from a list colormap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["red", "violet", "blue"]) # Plotting the points with the custom colormap plt.scatter(x, y, c=c, cmap=colormap, norm=norm) # Adding a color scale to the plot plt.colorbar() plt.show()
This method ensures a seamless color transition between the specified values.
Further customization is possible by supplying tuples of normalized values and corresponding colors to the from_list method.
# Custom values and colors custom_values = [-2, -1, 2] custom_colors = ["red", "violet", "blue"] # Generating a segmented colormap from custom tuples colormap = matplotlib.colors.LinearSegmentedColormap.from_list("", list(zip(map(norm, custom_values), custom_colors))) # Applying the colormap to the plot plt.scatter(x, y, c=c, cmap=colormap, norm=norm) plt.colorbar() plt.show()
By utilizing this technique, you can create personalized colormaps that precisely represent your data.
The above is the detailed content of How to Create Custom Colormaps and Color Scales with Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!