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()
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!