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

对数刻度下如何用EngFormatter设置次要刻度标签且不新增多余标签?

Matplotlib对数Y轴自定义刻度标签(保留刻度数量)

核心思路

保留对数轴原有的主次刻度线数量(不改变刻度位置),通过自定义格式化器精准控制标签显示:

  • 主刻度沿用EngFormatter实现工程化格式(如“1 k”“10 k”)
  • 次刻度仅显示你需要的特定值标签,其余隐藏

代码实现

import matplotlib.pyplot as plt
from matplotlib.ticker import EngFormatter, FuncFormatter

# 生成示例数据
x = [1, 2, 3]
y = [1000, 6000, 10000]

fig, ax = plt.subplots()
ax.plot(x, y)

# 设置对数Y轴
ax.set_yscale('log')

# 初始化工程格式化器(自动识别量级,如k代表千)
eng_formatter = EngFormatter(unit='')

# 主刻度应用EngFormatter
ax.yaxis.set_major_formatter(eng_formatter)

# 获取主刻度位置(用于后续判断)
major_ticks = ax.yaxis.get_major_locator()()
# 定义需要额外显示的次刻度值(比如你需要的6000)
extra_show_ticks = [6000]

# 自定义次刻度格式化器
def custom_minor_formatter(x, pos):
    # 仅主刻度和指定次刻度显示标签,其余返回空字符串(隐藏标签)
    if x in major_ticks or x in extra_show_ticks:
        return eng_formatter.format_data(x)
    return ''

# 次刻度应用自定义格式化器
ax.yaxis.set_minor_formatter(FuncFormatter(custom_minor_formatter))

plt.show()

灵活调整

  • 如果想显示所有整数千的次刻度标签,把判断条件改成if x % 1000 == 0:即可
  • 如果不需要额外显示次刻度,直接把次刻度格式化器设为空:ax.yaxis.set_minor_formatter(FuncFormatter(lambda x, pos: '')),只保留主刻度标签

内容的提问来源于stack exchange,提问作者Ilya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 09:11:09