How to Set Color of Scatter Plot in Matplotlib Easily
To set the color of a scatter plot in Matplotlib, use the
c or color parameter inside plt.scatter(). You can pass a single color name, a list of colors, or a colormap to customize the points' colors.Syntax
The basic syntax to set color in a scatter plot is:
plt.scatter(x, y, c=color)wherecolorcan be a single color string, a list of colors, or numeric values for colormapping.plt.scatter(x, y, color=color)also works for a single color.
Here, x and y are data points. The c parameter controls the color of each point.
python
plt.scatter(x, y, c=color) plt.scatter(x, y, color=color)
Example
This example shows how to set a single color and multiple colors for scatter plot points.
python
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [5, 4, 3, 2, 1] # Single color for all points plt.scatter(x, y, color='red') plt.title('Scatter plot with single color') plt.show() # Multiple colors for each point colors = ['red', 'green', 'blue', 'orange', 'purple'] plt.scatter(x, y, c=colors) plt.title('Scatter plot with multiple colors') plt.show()
Output
Two scatter plots displayed: first all points red, second points colored red, green, blue, orange, purple respectively.
Common Pitfalls
Common mistakes when setting scatter plot colors include:
- Using
colorwith a list of colors instead ofc. Thecolorparameter expects a single color, whileccan accept a list. - Passing numeric values to
cwithout specifying a colormap, which may cause unexpected colors. - Using invalid color names or formats.
Correct usage example:
python
import matplotlib.pyplot as plt x = [1, 2, 3] y = [3, 2, 1] colors = ['red', 'green', 'blue'] # Wrong: color expects a single color, not a list # plt.scatter(x, y, color=colors) # This will raise an error # Right: use c for list of colors plt.scatter(x, y, c=colors) plt.show()
Output
Scatter plot with points colored red, green, and blue respectively.
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| c | Color or sequence of colors for points | 'red', ['red', 'blue'], numeric array |
| color | Single color for all points | 'green', '#FF00FF' |
| cmap | Colormap used when c is numeric | 'viridis', 'plasma' |
| alpha | Transparency level (0 to 1) | 0.5 for half transparent |
Key Takeaways
Use the 'c' parameter to set colors for individual scatter plot points.
Pass a single color string to 'color' for uniform point color.
Provide a list of colors to 'c' to color points differently.
Use numeric values with 'c' and specify 'cmap' for color gradients.
Avoid passing a list to 'color' as it expects a single color.