0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Add Colorbar in Matplotlib: Simple Guide

To add a colorbar in matplotlib, use the plt.colorbar() function after creating a plot with a mappable object like imshow or scatter. The colorbar visually represents the mapping of colors to data values in your plot.
๐Ÿ“

Syntax

The basic syntax to add a colorbar in matplotlib is:

  • plt.colorbar(mappable=None, ax=None, orientation='vertical')

Where:

  • mappable: The image or plot object that has color data (like the result of imshow or scatter).
  • ax: The axes to which the colorbar applies (optional).
  • orientation: Direction of the colorbar, either 'vertical' (default) or 'horizontal'.
python
import matplotlib.pyplot as plt
import numpy as np

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

# Create an image plot
img = plt.imshow(Z)

# Add colorbar for the image
plt.colorbar(img, orientation='vertical')

plt.show()
๐Ÿ’ป

Example

This example shows how to create a heatmap with imshow and add a vertical colorbar to explain the color scale.

python
import matplotlib.pyplot as plt
import numpy as np

# Generate random data
data = np.random.rand(5, 5)

# Plot heatmap
heatmap = plt.imshow(data, cmap='viridis')

# Add colorbar
plt.colorbar(heatmap)

plt.title('Heatmap with Colorbar')
plt.show()
Output
A window showing a 5x5 colored grid with a vertical colorbar on the right side indicating the color scale from low to high values.
โš ๏ธ

Common Pitfalls

Common mistakes when adding colorbars include:

  • Not passing the mappable object (like the result of imshow) to plt.colorbar(), which causes no colorbar to appear.
  • Adding multiple colorbars unintentionally by calling plt.colorbar() multiple times without specifying axes.
  • Using plots that do not support color mapping directly, so colorbar has no reference.

Correct usage requires passing the plot object that contains color data.

python
import matplotlib.pyplot as plt
import numpy as np

# Wrong way: missing mappable
plt.imshow(np.random.rand(5,5))
plt.colorbar()  # Works here because plt.imshow returns mappable

# Wrong way: colorbar without mappable on scatter
plt.scatter([1,2,3], [4,5,6])
# plt.colorbar()  # This will raise an error because scatter returns PathCollection, need to assign and pass

# Right way:
sc = plt.scatter([1,2,3], [4,5,6], c=[10,20,30], cmap='plasma')
plt.colorbar(sc)  # Pass scatter object
plt.show()
Output
A scatter plot with points colored by values and a colorbar showing the color scale.
๐Ÿ“Š

Quick Reference

Tips for adding colorbars in matplotlib:

  • Always save the plot object (mappable) when creating plots with color data.
  • Pass the mappable object to plt.colorbar() to link the colorbar correctly.
  • Use orientation='horizontal' for horizontal colorbars.
  • Use ax parameter to place colorbar in specific subplot axes.
โœ…

Key Takeaways

Use plt.colorbar() with the mappable plot object to add a colorbar.
Always assign the plot with color data to a variable and pass it to plt.colorbar().
Colorbars help interpret the color scale of your data visualization.
Specify orientation and axes to customize colorbar placement.
Avoid calling plt.colorbar() without a mappable to prevent errors.