如何优化近0值占比高的等高线图并实现类瀑布图效果?
Solution
To fix your contour plot and achieve the desired waterfall-style visualization with a blue background and prominent meaningful data, apply these adjustments:
Key Fixes:
- Use
SymLogNorminstead ofNormalizeorLogNormto handle zero values while preserving visibility of 1e-7 range data. - Replace zero values with a tiny positive number to avoid log scaling errors.
- Define custom color levels to focus on your critical value ranges.
- Combine
contourf(filled background) andcontour(top lines) for the waterfall effect.
Modified Code:
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import SymLogNorm X, Y = np.meshgrid(frequencies, speeds) Z = freq_speed_grid.to_numpy() # Replace zeros with a small positive value to enable log scaling Z[Z == 0] = 1e-8 plt.figure(figsize=(10, 5)) # SymLogNorm handles zero/near-zero values and log scales for larger data norm = SymLogNorm(linthresh=1e-7, vmin=1e-8, vmax=Z.max(), base=10) # Custom levels to emphasize the 1e-7 range and meaningful data levels = np.concatenate([ np.linspace(1e-7, 1e-6, 10), # Dense levels for low-value range np.linspace(1e-6, Z.max(), 40) # Sparser levels for higher values ]) # Filled contour for blue background (low values) plt.contourf(X, Y, Z, cmap="jet", norm=norm, levels=levels, extend="min") # Overlay white contour lines to highlight data boundaries plt.contour(X, Y, Z, colors="white", linewidths=0.5, levels=levels) plt.colorbar(label="Magnitude") plt.xlabel("Frequency (Hz)") plt.ylabel("Speed (RPM)") plt.show()
Explanation:
- SymLogNorm: Maps zero/near-zero values to the blue background via linear scaling near
linthresh=1e-7, while using log scaling for larger values to preserve detail in meaningful data. - Zero Replacement: Prevents
LogNorm's all-white issue by giving zeros a non-zero value that maps to the lowest color in the colormap. - Custom Levels: Concentrates more levels around 1e-7 to enhance color differentiation in that critical range, making subtle variations visible.
- Contour Overlay: White lines on top of the filled contour mimic the waterfall plot's distinct, easy-to-read data boundaries.
内容的提问来源于stack exchange,提问作者Firas Bejar
相关产品推荐
相关产品推荐

