How to Use Colormap in Scatter Plots with Matplotlib
Use the
c parameter in plt.scatter() to pass values that determine the colors of points, and set the cmap parameter to a colormap name like 'viridis'. This colors the scatter points based on the data values you provide.Syntax
The basic syntax to use a colormap in a scatter plot is:
plt.scatter(x, y, c=values, cmap='colormap_name')
Here, x and y are coordinates, c is an array of values that control the color of each point, and cmap is the name of the colormap to apply.
python
plt.scatter(x, y, c=values, cmap='viridis')Example
This example shows how to create a scatter plot with points colored by their y-values using the 'plasma' colormap.
python
import matplotlib.pyplot as plt import numpy as np # Create data x = np.linspace(0, 10, 100) y = np.sin(x) # Use y values to color points plt.scatter(x, y, c=y, cmap='plasma') plt.colorbar(label='Value of y') plt.title('Scatter plot with colormap') plt.xlabel('x') plt.ylabel('y') plt.show()
Output
A scatter plot window showing points along a sine curve colored from dark purple to yellow according to their y-value, with a colorbar on the side.
Common Pitfalls
- Not passing a numeric array to
cwill cause errors or unexpected colors. - For categorical data, colormaps may not work well; use discrete colors instead.
- For better color interpretation, always add
plt.colorbar()to show the color scale. - Using
cmapwithoutchas no effect.
python
import matplotlib.pyplot as plt x = [1, 2, 3] y = [4, 5, 6] # Wrong: c is a list of strings (will error) # plt.scatter(x, y, c=['red', 'green', 'blue'], cmap='viridis') # Right: c is numeric plt.scatter(x, y, c=[10, 20, 30], cmap='viridis') plt.colorbar() plt.show()
Output
A scatter plot with three points colored from blue to yellow according to values 10, 20, 30, with a colorbar.
Quick Reference
Tips for using colormaps in scatter plots:
- Use
cto provide numeric values for coloring. - Choose a colormap with
cmap, e.g., 'viridis', 'plasma', 'inferno', 'magma'. - Add
plt.colorbar()to show the color scale. - Normalize data if needed using
matplotlib.colors.Normalize.
Key Takeaways
Use the 'c' parameter in plt.scatter() to assign colors based on data values.
Set the 'cmap' parameter to choose the colormap for coloring points.
Always add plt.colorbar() to help interpret the color scale.
Ensure the 'c' values are numeric for proper colormap application.
Colormaps are best for continuous numeric data, not categorical.