如何为matplotlib中的tricontour图设置颜色条显示范围?
解决matplotlib tricontourf颜色条范围设置无效的问题
问题描述
希望设置右侧颜色条的范围,当前使用的代码如下:
fig, (ax1) = plt.subplots(nrows=1, figsize=(8, 6), dpi=dpi, facecolor='w', edgecolor='k') ax1.tricontour(x, y, c, levels=5, linewidths=0.5, colors='k') cntr = ax1.tricontourf(x, y, c, levels=20, cmap="RdBu_r") fig.colorbar(cntr, ax=ax1) ax1.plot(x, y, 'ko', ms=3) ax1.set(xlim=(-2, 10), ylim=(-2, 10)) ax1.set_title('Title') plt.savefig('plot.png',dpi=dpi) plt.show()
当前绘图效果:
尝试使用ax1.set(clim=(0.45,4.5))及类似写法,或设置vmin和vmax均无效。
问题根源
代码中tricontourf的levels=20会让matplotlib自动根据数据c的范围生成20个层级,此时单独设置clim、vmin/vmax无法覆盖自动生成的层级范围,导致颜色条范围未按预期调整。
解决方案
方案1:手动指定层级范围
使用numpy.linspace生成目标范围内的等差层级,替换原levels参数,确保颜色填充和轮廓线的层级范围一致:
import numpy as np # ... 其他代码不变 # 生成0.45到4.5之间的5个轮廓线层级、20个填充层级 contour_levels = np.linspace(0.45, 4.5, 5) fill_levels = np.linspace(0.45, 4.5, 20) ax1.tricontour(x, y, c, levels=contour_levels, linewidths=0.5, colors='k') cntr = ax1.tricontourf(x, y, c, levels=fill_levels, cmap="RdBu_r")
方案2:使用Normalize对象限制颜色映射范围
通过matplotlib.colors.Normalize指定vmin和vmax,传给tricontourf和tricontour的norm参数,让层级基于该范围生成:
from matplotlib.colors import Normalize # ... 其他代码不变 norm = Normalize(vmin=0.45, vmax=4.5) ax1.tricontour(x, y, c, levels=5, linewidths=0.5, colors='k', norm=norm) cntr = ax1.tricontourf(x, y, c, levels=20, cmap="RdBu_r", norm=norm)
完整修改后代码示例
import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import Normalize # 替换为你的实际数据 x = np.random.uniform(-2, 10, 100) y = np.random.uniform(-2, 10, 100) c = np.random.uniform(0, 5, 100) dpi = 100 fig, (ax1) = plt.subplots(nrows=1, figsize=(8, 6), dpi=dpi, facecolor='w', edgecolor='k') # 选择方案1或方案2,注释掉另一个 # --- 方案1 开始 --- contour_levels = np.linspace(0.45, 4.5, 5) fill_levels = np.linspace(0.45, 4.5, 20) ax1.tricontour(x, y, c, levels=contour_levels, linewidths=0.5, colors='k') cntr = ax1.tricontourf(x, y, c, levels=fill_levels, cmap="RdBu_r") # --- 方案1 结束 --- # --- 方案2 开始 --- # norm = Normalize(vmin=0.45, vmax=4.5) # ax1.tricontour(x, y, c, levels=5, linewidths=0.5, colors='k', norm=norm) # cntr = ax1.tricontourf(x, y, c, levels=20, cmap="RdBu_r", norm=norm) # --- 方案2 结束 --- fig.colorbar(cntr, ax=ax1) ax1.plot(x, y, 'ko', ms=3) ax1.set(xlim=(-2, 10), ylim=(-2, 10)) ax1.set_title('Title') plt.savefig('plot.png',dpi=dpi) plt.show()
内容的提问来源于stack exchange,提问作者senorscience
相关产品推荐
相关产品推荐

