How to Set a Custom 0‑17 Colorbar Range in Matplotlib Contour Plots
This article walks through a Python community member's question about configuring a Matplotlib contour plot's colorbar to display values from 0 to 17, presents two code attempts, and provides a working solution using a custom ScalarMappable with defined tick levels.
Introduction
In a Python community, a user asked how to set the colorbar range of a plt.contour() plot to display values from 0 to 17.
First Attempt
The initial code used cbar.set_ticks(np.linspace(0, 10, 10)) and adjusted limits, but it could not achieve the required 0‑17 range.
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x, y)
data = 2 * (np.sin(X) + np.sin(3 * Y))
fig, ax = plt.subplots()
contour = ax.contour(X, Y, data)
cbar = fig.colorbar(contour, ax=ax)
cbar.set_ticks(np.linspace(0, 10, 10)) # Set 10 ticks from 0 to 10 (inclusive)
# cbar.set_ticklabels([f'{i:.1f}' for i in np.linspace(0, 10, 10)]) # Set tick labels
cbar.ax.set_ylim(0, 10) # Set the limits of the colorbar
plt.show()Even after setting the limits to 10, the user needed a colorbar that spanned 0‑17 while the data’s maximum value was 1.
Working Solution – Custom Colorbar
A second approach creates a separate ScalarMappable, sets its clim to (0, 17), defines specific tick levels, and places the colorbar on the right side.
import matplotlib.pyplot as plt
import matplotlib.cm as cm
fig, ax = plt.subplots(1, 1, figsize=(10, 6))
# Create a ScalarMappable object for the colorbar
sm = cm.ScalarMappable(cmap=plt.get_cmap('viridis'))
sm.set_clim(0, 17)
# Define tick positions (levels)
levels = [0, 4, 8, 12, 17]
# Create the colorbar with custom ticks and label
cbar = fig.colorbar(sm, ax=ax, orientation='vertical',
label='Data Value', ticks=levels)
plt.show()The resulting plot shows a colorbar with the desired range, although the visual appearance may differ from the original contour plot.
Conclusion
The discussion demonstrates how to customize Matplotlib colorbars for contour plots, providing a practical solution for setting specific value ranges.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
