Add a colorbar to a Matplotlib scatter plot

Python

Matplotlib

Scatter

Add colorbar

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 marker colors based on numerical data, we can use a colorbar to show the value associated with each color.

Code Example

Pass numerical data as the c parameter to plt.scatter() to vary the marker colors. Matplotlib uses a color map to map numerical values to colors. Use the cmap parameter to choose the type of color map, there are many others to chose from. Finally, call plt.colorbar() to add a color bar to the figure.

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]
marker_colors = [70, 70, 30, 10, 70, 60, 80, 20]

# Add a color bar here
plt.scatter(x_values, y_values, c=marker_colors, cmap="inferno")
plt.colorbar()

plt.show()

png