A colorbar shows the scale of colors in a plot. Positioning it well helps people understand the data better.
0
0
Colorbar positioning in Matplotlib
Introduction
When you have a heatmap and want to show what colors mean.
When you create a scatter plot with colors representing values.
When you want to place the colorbar on the side or bottom for better space use.
When you want to avoid the colorbar covering important parts of the plot.
Syntax
Matplotlib
plt.colorbar(mappable, ax=None, orientation='vertical', fraction=0.15, pad=0.05, location='right')
mappable is the plot object with colors (like an image or scatter).
orientation can be 'vertical' or 'horizontal'.
location sets where the colorbar appears: 'right', 'left', 'top', or 'bottom'.
Examples
Places a vertical colorbar on the right side of the plot.
Matplotlib
plt.colorbar(im, orientation='vertical', location='right')
Places a horizontal colorbar below the plot.
Matplotlib
plt.colorbar(im, orientation='horizontal', location='bottom')
Places a smaller colorbar on the left with some space from the plot.
Matplotlib
plt.colorbar(im, fraction=0.05, pad=0.1, location='left')
Sample Program
This code makes a 10x10 heatmap with random values. It adds a vertical colorbar on the right side labeled 'Intensity'.
Matplotlib
import matplotlib.pyplot as plt import numpy as np # Create data np.random.seed(0) data = np.random.rand(10, 10) # Create heatmap fig, ax = plt.subplots() im = ax.imshow(data, cmap='viridis') # Add colorbar on the right cbar = plt.colorbar(im, ax=ax, orientation='vertical', location='right') cbar.set_label('Intensity') plt.show()
OutputSuccess
Important Notes
You can use location to move the colorbar to 'left', 'right', 'top', or 'bottom'.
Adjust fraction to change the size of the colorbar relative to the plot.
Use pad to add space between the plot and the colorbar.
Summary
Colorbars explain the meaning of colors in plots.
You can position colorbars on any side using location.
Adjust size and spacing with fraction and pad.