Using colormaps in Matplotlib is a simple process. You can set the color map of a plot using the cmap keyword argument of various Matplotlib functions. In this section, we will discuss how to use colormaps in Matplotlib using some examples.
Example 1: Scatter Plot
Suppose you have two arrays, x and y, and you want to create a scatter plot of these two arrays with colors determined by a third array z. You can use the scatter function in Matplotlib to create the plot and set the color map using the cmap keyword argument.
import matplotlib.pyplot as plt import numpy as np # create data x = np.random.rand(100) y = np.random.rand(100) z = np.random.rand(100) # create scatter plot with color determined by z values plt.scatter(x, y, c=z, cmap='viridis') plt.colorbar() # show the plot plt.show()
In this example, we have used the viridis color map to colorize the scatter plot based on the z array’s values. The colorbar function is used to add a colorbar to the plot that shows the color values corresponding to the data values.
Example 2: Contour Plot
Suppose you have two arrays, x and y, and you want to create a contour plot of a function f(x,y) with colors determined by the function’s values. You can use the contourf function in Matplotlib to create the plot and set the color map using the cmap keyword argument.
import matplotlib.pyplot as plt import numpy as np # create data x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = np.sin(np.sqrt(X**2 + Y**2)) # create contour plot with color determined by Z values plt.contourf(X, Y, Z, cmap='coolwarm') plt.colorbar() # show the plot plt.show()
In this example, we have used the coolwarm color map to colorize the contour plot based on the Z function’s values. The colorbar function is used to add a colorbar to the plot that shows the color values corresponding to the data values.
Using colormaps in Matplotlib is a simple process that involves setting the cmap keyword argument of various Matplotlib functions. By choosing an appropriate colormap, you can create visually appealing and informative data visualizations that effectively communicate your data.