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
Setting the limits on a colorbar of a contour plot in Matplotlib
When creating contour plots in Matplotlib, you can control the color range by setting limits on the colorbar. This allows you to focus on specific data ranges and maintain consistent color scales across multiple plots.
Basic Approach
To set colorbar limits on a contour plot, follow these steps ?
- Create coordinate data using NumPy
- Generate a meshgrid for contour plotting
- Set vmin and vmax parameters to define the color range
- Use contourf() with these limits
- Create a colorbar with ScalarMappable for custom ticks
Example
Here's how to create a contour plot with custom colorbar limits ?
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.cm import ScalarMappable
# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create coordinate data
x = np.arange(20)
y = np.arange(20)
# Generate data matrix
data = x[:, None] + y[None, :]
X, Y = np.meshgrid(x, y)
# Set colorbar limits
vmin = 0
vmax = 15
# Create contour plot
fig, ax = plt.subplots()
qcs = ax.contourf(
X, Y, data,
vmin=vmin, vmax=vmax
)
# Add colorbar with custom ticks
fig.colorbar(
ScalarMappable(norm=qcs.norm, cmap=qcs.cmap),
ticks=range(vmin, vmax+5, 5)
)
plt.show()
The output shows a contour plot where colors are mapped only to values between 0 and 15, even though the actual data ranges from 0 to 38.
Alternative Method
You can also set colorbar limits directly on the contour plot ?
import matplotlib.pyplot as plt
import numpy as np
# Create data
x = np.linspace(0, 4*np.pi, 50)
y = np.linspace(0, 4*np.pi, 50)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
# Create contour plot with limits
fig, ax = plt.subplots()
cs = ax.contourf(X, Y, Z, levels=20, vmin=-0.5, vmax=0.5)
# Add colorbar
cbar = fig.colorbar(cs)
cbar.set_label('Values')
plt.title('Contour Plot with Limited Colorbar Range')
plt.show()
This approach clips the color range to focus on values between -0.5 and 0.5, making subtle variations more visible.
Key Parameters
| Parameter | Description | Usage |
|---|---|---|
vmin |
Minimum value for colorbar | Sets lower color limit |
vmax |
Maximum value for colorbar | Sets upper color limit |
levels |
Number of contour levels | Controls color resolution |
Conclusion
Setting colorbar limits using vmin and vmax parameters helps focus on specific data ranges and ensures consistent color scaling across plots. Use ScalarMappable for advanced colorbar customization with custom tick marks.
