Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to add Matplotlib Colorbar Ticks?
A colorbar in Matplotlib displays the color scale used in a plot. By default, Matplotlib automatically places ticks on the colorbar, but you can customize these ticks to show specific values or improve readability.
Basic Colorbar with Custom Ticks
Here's how to add custom ticks to a colorbar using np.linspace() ?
import numpy as np import matplotlib.pyplot as plt # Set figure size plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create data x, y = np.mgrid[-1:1:100j, -1:1:100j] z = (x + y) * np.exp(-5.0 * (x ** 2 + y ** 2)) # Display the data as an image plt.imshow(z, extent=[-1, 1, -1, 1]) # Create custom ticks between min and max values ticks = np.linspace(z.min(), z.max(), 5, endpoint=True) # Add colorbar with custom ticks cb = plt.colorbar(ticks=ticks) plt.show()
Adding Tick Labels
You can also customize the tick labels to show formatted values ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
data = np.random.randn(10, 10)
# Create the plot
im = plt.imshow(data, cmap='viridis')
# Define custom tick positions
tick_positions = [-2, -1, 0, 1, 2]
# Define custom tick labels
tick_labels = ['Very Low', 'Low', 'Medium', 'High', 'Very High']
# Add colorbar with custom ticks and labels
cb = plt.colorbar(im, ticks=tick_positions)
cb.set_ticklabels(tick_labels)
plt.title('Colorbar with Custom Tick Labels')
plt.show()
Controlling Tick Parameters
You can further customize the appearance of colorbar ticks ?
import numpy as np
import matplotlib.pyplot as plt
# Create data
data = np.random.uniform(0, 100, (8, 8))
# Create plot
im = plt.imshow(data, cmap='plasma')
# Add colorbar with many ticks
ticks = np.arange(0, 101, 10) # Ticks every 10 units
cb = plt.colorbar(im, ticks=ticks)
# Customize tick parameters
cb.ax.tick_params(labelsize=8, rotation=45)
cb.set_label('Values', rotation=270, labelpad=15)
plt.title('Colorbar with Rotated Tick Labels')
plt.show()
Key Parameters
| Parameter | Description | Example |
|---|---|---|
ticks |
Positions where ticks appear | ticks=[0, 0.5, 1] |
set_ticklabels() |
Custom labels for ticks | cb.set_ticklabels(['Low', 'High']) |
tick_params() |
Customize tick appearance | cb.ax.tick_params(labelsize=10) |
Conclusion
Use plt.colorbar(ticks=ticks) to specify custom tick positions. Combine with set_ticklabels() for custom labels and tick_params() for styling control.
Advertisements
