0
0
Matplotlibdata~5 mins

Colorbar configuration in Matplotlib

Choose your learning style9 modes available
Introduction

A colorbar shows the scale of colors used in a plot. It helps us understand what the colors mean in numbers.

When you have a heatmap and want to show what values the colors represent.
When plotting data with colors that represent different ranges, like temperature or elevation.
When you want to add a legend for colors in scatter plots or images.
When you want to customize the look or position of the color scale in your plot.
Syntax
Matplotlib
import matplotlib.pyplot as plt

# Create a plot with a colorbar
im = plt.imshow(data)
cb = plt.colorbar(im, orientation='vertical', fraction=0.046, pad=0.04)

# Customize colorbar
cb.set_label('Label text')
cb.set_ticks([0, 0.5, 1])
cb.ax.tick_params(labelsize=10)

plt.colorbar()

You can change orientation with orientation='vertical' or 'horizontal'.

Examples
Adds a default vertical colorbar for the image im.
Matplotlib
plt.colorbar(im)
Adds a horizontal colorbar below the plot.
Matplotlib
plt.colorbar(im, orientation='horizontal')
Adds a colorbar and sets a label describing the data.
Matplotlib
cb = plt.colorbar(im)
cb.set_label('Temperature (°C)')
Sets specific tick marks on the colorbar.
Matplotlib
cb = plt.colorbar(im)
cb.set_ticks([0, 0.5, 1])
Sample Program

This code creates a 10x10 grid of random numbers and shows it as a colored image. The colorbar on the right explains the color scale from 0 to 1 with ticks at 0, 0.5, and 1. The label 'Random values' describes what the colors mean.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

# Create sample data
np.random.seed(0)
data = np.random.rand(10, 10)

# Plot the data as an image
im = plt.imshow(data, cmap='viridis')

# Add a vertical colorbar with label and custom ticks
cb = plt.colorbar(im, orientation='vertical', fraction=0.046, pad=0.04)
cb.set_label('Random values')
cb.set_ticks([0, 0.5, 1])
cb.ax.tick_params(labelsize=8)

plt.title('Heatmap with Colorbar')
plt.show()
OutputSuccess
Important Notes

You can control the size and position of the colorbar using fraction and pad parameters.

Use cb.ax.tick_params() to change tick label size and style.

Colorbar orientation can be vertical or horizontal depending on your plot layout.

Summary

A colorbar helps explain the meaning of colors in your plot.

Use plt.colorbar() to add and customize it.

You can change orientation, labels, and ticks to make it clear.