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

Matplotlib双对数图自定义刻度:仅显示指定值且无科学计数法

解决Matplotlib双对数图X轴多余刻度问题

你的代码仅设置了set_xticks([1,5,10]),但对数轴默认的刻度生成器会自动添加额外刻度,所以才出现了多余标签。要实现只保留1、5、10三个刻度且标签为标准格式,需要两步操作:固定刻度位置,替换刻度格式化器。

修改后的完整代码:

import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, FixedLocator

plt.errorbar(x = [1, 2, 4, 8, 10],
             y = [1, 1/2, 1/4, 1/8, 1/16 ],
             yerr = [0.05, 0.05, 0.05, 0.05, 0.05],
             fmt='o', capsize=2)
axes=plt.gca()
axes.set_xlim([1, 10])
axes.set_ylim([10**(-2),2])
axes.set_xscale('log')
axes.set_yscale('log')

# 强制固定X轴主刻度位置,仅保留指定的三个值
axes.xaxis.set_major_locator(FixedLocator([1,5,10]))
# 使用ScalarFormatter生成常规数字标签,关闭科学计数法和偏移量
formatter = ScalarFormatter()
formatter.set_scientific(False)
formatter.set_useOffset(False)
axes.xaxis.set_major_formatter(formatter)

plt.show()

关键说明:

  • FixedLocator([1,5,10]):替代默认的对数刻度定位器,强制只在指定位置显示刻度,彻底消除多余刻度。
  • ScalarFormatter:替换对数轴默认的格式化器,确保标签显示为常规数字(如1、5、10),而非科学计数法格式;set_scientific(False)和set_useOffset(False)用于避免自动切换成科学计数法或添加偏移量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:35:10