Set Colorbar Range in matplotlib
Last Updated :
12 Apr, 2025
When working with plots, colorbars are often used to show how data values correspond to colors on the plot. Sometimes the default color scale might not represent the data well or might not fit the range we need. In such cases, setting a specific colorbar range becomes essential. In this article, we’ll explore how to control the color range in Matplotlib. By adjusting the color range, we can better highlight specific sections of the data and make our plots more informative.
What is a Colorbar?
A colorbar is a small box shown alongside a plot that indicates how colors represent different values in our data. For example, in a heatmap, each color corresponds to a numerical value. By looking at the colorbar, we can understand which value each color represents.
Need for setting a Colorbar Range
- Focus on a Specific Range of Values: If we’re interested in a particular range of our data (e.g. values between 10 and 30), setting a colorbar range helps highlight that area while ignoring extreme values.
- Ensure Consistency Across Multiple Plots: When comparing multiple plots, setting a fixed colorbar range ensures the same color corresponds to the same value across all plots, making comparisons clearer.
- Handle Extreme Data Variance: If our data contains outliers or extreme values, setting a colorbar range helps avoid distortion in how the colors represent our data, making the plot more readable and accurate.
Below is the step-by-step implementation of setting a colorbar range in Matplotlib:
1. Importing Libraries
We will be using Matplotlib and NumPy for creating the plot and manipulating the data.
Python
import numpy as np
import matplotlib.pyplot as plt
2. Setting Up Some Generic Data
We define the size of the grid and create x
and y
arrays using np.mgrid
. We then calculate Z
, which is a combination of sine and cosine functions.
Python
N = 37
x, y = np.mgrid[:N, :N]
Z = (np.cos(x*0.2) + np.sin(y*0.3))
x, y = np.mgrid[:N, :N]
creates two 2D arrays of shape (37, 37)
that represent coordinates.Z
is computed as a combination of the cosine of x
and the sine of y
, which will give us a grid of values based on the trigonometric functions.
3. Masking Out Negative and Positive Values
We use np.ma.masked_less
and np.ma.masked_greater
to mask values below 0 and above 0, respectively. This allows us to plot only positive and negative values separately.
Python
Zpositive = np.ma.masked_less(Z, 0) # Mask all values less than 0
Znegative = np.ma.masked_greater(Z, 0) # Mask all values greater than 0
np.ma.masked_less(Z, 0)
masks all values in Z
that are less than 0 (i.e.making negative values invisible).np.ma.masked_greater(Z, 0)
masks all values in Z
that are greater than 0 (i.e. making positive values invisible).
4. Creating Subplots
We set up a figure with three subplots (side by side) using plt.subplots
.
Python
fig, (ax1, ax2, ax3) = plt.subplots(figsize=(13, 3), ncols=3)
figsize=(13, 3)
: Specifies the size of the entire figure.ncols=3
: Specifies that there will be 3 columns of plots.
5. Plotting Just the Positive Data
We plot only the positive values of Z
on the first subplot using the Blues colormap.
Python
pos = ax1.imshow(Zpositive, cmap='Blues')
fig.colorbar(pos, ax=ax1)
ax1.imshow(Zpositive, cmap='Blues')
: Plots the positive values of Z
using the 'Blues'
colormap.fig.colorbar(pos, ax=ax1)
: Adds a colorbar specific to the ax1
plot, which helps to interpret the colors.
6. Plotting Just the Negative Data
We plot only the negative values of Z
on the second subplot using the Reds_r colormap.
Python
neg = ax2.imshow(Znegative, cmap='Reds_r')
fig.colorbar(neg, ax=ax2)
ax2.imshow(Znegative, cmap='Reds_r')
: Plots the negative values of Z
using the 'Reds_r'
colormap (note the _r
to reverse the colors).fig.colorbar(neg, ax=ax2)
: Adds a colorbar for the negative values.
7. Plotting Both Positive and Negative Values
In the third subplot, we plot both positive and negative values of Z
with a color range clipped between -1.2 and 1.2.
Python
pos_neg_clipped = ax3.imshow(Z, cmap='RdBu', vmin=-1.2, vmax=1.2)
color_bar = fig.colorbar(pos_neg_clipped, ax=ax3, extend='both')
color_bar.minorticks_on()
ax3.imshow(Z, cmap='RdBu', vmin=-1.2, vmax=1.2)
: Plots both positive and negative values of Z
using the RdBu
colormap and clips the color range between -1.2 and 1.2.fig.colorbar(pos_neg_clipped, ax=ax3, extend='both')
: Adds a colorbar for this plot, with extend='both'
to indicate that the color scale extends beyond the clipped values.color_bar.minorticks_on()
: Enables minor ticks on the colorbar to help read the values more precisely.
8. Displaying the Plot
Finally, we display the figure with all the subplots.
Python
Output:

Result
This code demonstrates how to visualize and differentiate positive and negative values in a dataset using distinct color schemes and how to control the color range for better clarity. By utilizing masked arrays and colorbars, we ensure that the plot highlights relevant data efficiently, making the visualization more informative and easier to interpret.