Matplotlib 3.5.1中Contourf色条刻度标签格式异常问题
解决Matplotlib Contourf对数色条刻度显示为10的幂次格式问题
在Matplotlib 3.5.1环境下,使用contourf结合LogNorm绘制对数刻度等高线图时,色条刻度默认以小数格式(如0.0001)显示,而非官网示例中的10的幂次科学计数法格式。仅设置LogLocator无法解决格式问题,需同时配置对应的刻度格式化器。
完整解决方案代码
import matplotlib.pyplot as plt import numpy as np import matplotlib.colors as mcolors import matplotlib.ticker as mticker # 生成样本数据 x = np.linspace(-3.0, 3.0, 100) y = np.linspace(-3.0, 3.0, 100) X, Y = np.meshgrid(x, y) Z = np.exp(-X**2 - Y**2) # 创建对数归一化的等高线填充图 fig, ax = plt.subplots() contour = ax.contourf(X, Y, Z, levels=50, norm=mcolors.LogNorm()) # 添加色条并配置对数刻度格式 cbar = fig.colorbar(contour, ax=ax) cbar.set_label('Log scale color bar') # 设置对数刻度定位器 + 科学计数法格式化器 cbar.locator = mticker.LogLocator(base=10.0) cbar.formatter = mticker.LogFormatterSciNotation(base=10.0) cbar.update_ticks() plt.show()
关键说明
LogLocator:仅负责指定对数刻度的位置,不控制显示格式LogFormatterSciNotation:将刻度值转换为10^x形式的科学计数法,与官网示例格式一致- 若需要更美观的LaTeX数学排版格式,可替换格式化器为
LogFormatterMathtext:cbar.formatter = mticker.LogFormatterMathtext(base=10.0)
内容的提问来源于stack exchange,提问作者vercors
相关产品推荐
相关产品推荐

