Pyplot技术问询:如何制作带非线性刻度的离散色条?
Discrete Colorbar with Non-Linear Ticks in Matplotlib (No
contourf) Alright, let’s solve this problem properly. You need a discrete 5-color colorbar with non-linear scaling without relying on contourf—this approach works universally with most Matplotlib plot types (like scatter, pcolormesh, imshow) so you can adapt it to your use case.
Step-by-Step Approach
The core of the solution uses BoundaryNorm to map your data to discrete color bins, paired with a custom colormap. We’ll also manually configure non-linear ticks for the colorbar to match your bin boundaries.
Full Example Code
import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import BoundaryNorm, ListedColormap # ---------------------- # 1. Generate test data (replace with your actual data) # ---------------------- x = np.linspace(0, 10, 100) y = np.linspace(0, 10, 100) X, Y = np.meshgrid(x, y) # Create data with non-linear distribution (simulating real-world data) Z = np.exp(X/2) * np.sin(Y) Z = np.abs(Z) # Use positive values for easier binning # ---------------------- # 2. Define NON-LINEAR bin boundaries (5 bins = 6 boundaries) # Adjust these to match your desired non-linear scale! # ---------------------- bin_boundaries = [0, 1, 5, 20, 50, 100] num_bins = len(bin_boundaries) - 1 # Should be 5 # ---------------------- # 3. Create discrete colormap (5 custom colors) # ---------------------- custom_colors = [ "#ffcccc", # Light red "#ff9999", # Red "#ff6666", # Darker red "#cc0000", # Deep red "#990000" # Almost black red ] cmap = ListedColormap(custom_colors) # ---------------------- # 4. Create BoundaryNorm to map data to discrete bins # ---------------------- norm = BoundaryNorm(bin_boundaries, cmap.N, clip=True) # ---------------------- # 5. Plot your data (using pcolormesh here; swap for scatter/imshow as needed) # ---------------------- fig, ax = plt.subplots(figsize=(8, 6)) im = ax.pcolormesh(X, Y, Z, cmap=cmap, norm=norm) # ---------------------- # 6. Add colorbar with NON-LINEAR ticks # ---------------------- cbar = plt.colorbar(im, ax=ax) # Set ticks to the MIDPOINT of each bin (or use bin_boundaries if you prefer) cbar_ticks = [(bin_boundaries[i] + bin_boundaries[i+1])/2 for i in range(num_bins)] # Set tick labels to show the bin ranges (customize this as needed) cbar_ticklabels = [f"{bin_boundaries[i]}–{bin_boundaries[i+1]}" for i in range(num_bins)] cbar.set_ticks(cbar_ticks) cbar.set_ticklabels(cbar_ticklabels) cbar.set_label("Non-Linear Data Range") # Add plot labels ax.set_xlabel("X Axis") ax.set_ylabel("Y Axis") ax.set_title("Discrete Colorbar with Non-Linear Scaling (No contourf)") plt.tight_layout() plt.show()
Key Explanations
BoundaryNorm: This is the critical tool that turns continuous data into discrete color bins. It uses your non-linear boundaries to map each data point to the correct color—nocontourfrequired.- Custom Colormap:
ListedColormaplets you define exactly 5 distinct colors, ensuring you get a discrete colorbar instead of a gradient. - Non-Linear Ticks: By manually setting the colorbar ticks and labels, you can clearly communicate the non-linear bin ranges. You can swap midpoint ticks for the boundary values themselves if that fits your visualization better.
- Universal Compatibility: This method works with any plot function that accepts
cmapandnormparameters. For example, if you’re usingscatter, just passcmap=cmap, norm=normtoplt.scatter()and configure the colorbar the same way.
内容的提问来源于stack exchange,提问作者brzepkowski
相关产品推荐
相关产品推荐

