0
0
MatplotlibHow-ToBeginner ยท 3 min read

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) where color can 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 color with a list of colors instead of c. The color parameter expects a single color, while c can accept a list.
  • Passing numeric values to c without 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

ParameterDescriptionExample
cColor or sequence of colors for points'red', ['red', 'blue'], numeric array
colorSingle color for all points'green', '#FF00FF'
cmapColormap used when c is numeric'viridis', 'plasma'
alphaTransparency 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.