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

如何将Matplotlib中x轴刻度的科学计数法底数从10^5改为10^3?

解决Matplotlib X轴科学计数法强制以10^3为数量级的问题

要实现将X轴数值以103为倍数显示(如5×105转为500×10^3),可以通过两种方式自定义格式化器,以下是具体实现:

方法一:使用自定义函数格式化器(FuncFormatter)

这种方式灵活性最高,可完全控制刻度标签的显示样式:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

x = np.arange(0, 5e5, 10e3)
y = np.random.random_sample(len(x))

mm = 1 / 25.4

f, ax = plt.subplots(figsize=(210 * mm, 148 * mm), dpi=600)
ax.plot(x, y)

# 定义自定义格式化函数
def x_scaler(value, _):
    # 将数值除以10^3,用LaTeX格式排版科学计数法
    return f'${value / 1000:.0f} \\times 10^3$'

# 应用格式化器到X轴
ax.xaxis.set_major_formatter(FuncFormatter(x_scaler))

plt.show()

方法二:配置ScalarFormatter强制指定数量级

利用Matplotlib内置的ScalarFormatter,通过设置orderOfMagnitude属性强制使用10^3作为数量级:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

x = np.arange(0, 5e5, 10e3)
y = np.random.random_sample(len(x))

mm = 1 / 25.4

f, ax = plt.subplots(figsize=(210 * mm, 148 * mm), dpi=600)
ax.plot(x, y)

# 关闭默认自动选择数量级的科学计数法设置
ax.ticklabel_format(axis='x', style='plain')

# 配置ScalarFormatter
formatter = ScalarFormatter(useMathText=True)
formatter.set_powerlimits((0, 0))  # 强制始终显示科学计数法格式
formatter.orderOfMagnitude = 3  # 指定数量级为10^3
ax.xaxis.set_major_formatter(formatter)

plt.show()

关键说明

  • 原代码中ax.ticklabel_format()会自动选择最优数量级(此处为10^5),因此需要先关闭该设置(方法二中的style='plain'),再应用自定义格式化器。
  • 方法一中的FuncFormatter允许你完全自定义标签内容,若需要保留小数可修改:.0f为:.1f等格式。
  • 两种方法都兼容Python 3.9、Matplotlib 3.7及Jupyter Notebook环境。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 20:15:17