Individually change the scatter plot marker colors in Matplotlib

Python

Matplotlib

Scatter

Change marker colors

Luc B.

Python

Matplotlib

Scatter Plot

An easy way to create more expressive scatter plots is to style the markers so they visually encode additional data. By changing the color, size, and style of the markers, we can communicate more information and trends.

Code Example

Use the c parameter to plt.scatter() to change the marker colors. c can be a scalar to uniformly change the marker color, or it can be an array to modify the marker color individually.

By specifying a color map using the cmap parameter, c can be an array of numerical values that are mapped to colors. This allows the marker colors to represent an additional dimension of data.

import matplotlib.pyplot as plt

x_values = [20, 19, 16, 12, 19, 18, 22, 14]
y_values = [1, 0.91, 0.77, 0.67, 0.85, 0.78, 1.05, 0.63]

# Change the marker colors here
marker_colors = [70, 70, 30, 10, 70, 60, 80, 20]
plt.scatter(x_values, y_values, c=marker_colors, cmap='viridis')

# Add a colorbar
plt.colorbar()

plt.show()

png

This example uses the viridis color map, but there are many others to chose from. We also use plt.colorbar() to add a color bar to the figure, giving context to the colors.

More Examples

Without a Color Map

While the color map feature is useful, sometimes it is easier to manually specify the colors of each marker.

# Specify the color of each marker directly
marker_colors = ['r', 'b', 'r', 'r', 'r', 'b', 'r', 'b']
plt.scatter(x_values, y_values, c=marker_colors)

plt.show()

png

Valid color values are documented in the Matplotlib color reference.

Uniformly Change Marker Color

To change the color of all the markers, just pass a scalar value for c.

# Universally change the marker color
plt.scatter(x_values, y_values, c='orange')

plt.show()

png