You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 06:03:20