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

如何设置Matplotlib图表X轴为3的倍数科学计数法刻度?

解决Matplotlib X轴科学计数法刻度为10的3的负整数次幂的问题

要实现X轴刻度仅显示10的3的负整数次幂(如1e-3、1e-6、1e-9等)的科学计数法,同时匹配对应的轴范围,可通过以下两种方式实现:

方法一:使用工程符号格式化(自动匹配3的倍数指数)

Matplotlib的EngFormatter专门用于生成工程符号,其指数自动为3的整数倍,完美契合你需要的10的3的负整数次幂刻度风格。

示例代码(匹配1e-6刻度,范围0~300e-6)

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

# 生成时间数据:0到300e-6(30μs×10)
T = 30e-6
N = 10
time = np.linspace(0, N*T, num=N)

plt.plot(time, np.sin(time))
ax = plt.gca()

# 用工程符号格式化X轴,指定单位为秒(s),标签会自动显示为μs、ms等3的倍数指数形式
ax.xaxis.set_major_formatter(EngFormatter(unit='s'))

# 若需强制指定指数为-6(即1e-6),可添加参数exponent=-6
# ax.xaxis.set_major_formatter(EngFormatter(unit='s', exponent=-6, places=0))

plt.xlim(0, N*T)
plt.show()

示例代码(匹配1e-3刻度,范围0~0.3)

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

# 生成时间数据:0到0.3秒
time = np.linspace(0, 0.3, num=100)

plt.plot(time, np.sin(time))
ax = plt.gca()

# 工程符号格式化X轴,自动使用ms(1e-3)作为单位
ax.xaxis.set_major_formatter(EngFormatter(unit='s'))

plt.xlim(0, 0.3)
plt.show()

方法二:手动设置刻度位置与格式

如果需要精确控制刻度点为10的3的负整数次幂的倍数,可手动定义刻度位置,再通过自定义格式化函数生成对应标签。

示例代码(刻度为1e-6的倍数,范围0~300e-6)

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

# 生成时间数据
T = 30e-6
N = 10
time = np.linspace(0, N*T, num=N)

plt.plot(time, np.sin(time))
ax = plt.gca()

# 手动设置X轴刻度为0、100e-6、200e-6、300e-6
ax.set_xticks([0, 100e-6, 200e-6, 300e-6])

# 自定义格式化函数,将刻度值转换为1e-6的倍数并显示为科学计数法
def format_x_ticks(value, tick_num):
    scaled_value = value / 1e-6
    return f"{scaled_value:.0f}e-6"

ax.xaxis.set_major_formatter(FuncFormatter(format_x_ticks))

plt.show()

示例代码(刻度为1e-3的倍数,范围0~0.3)

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

# 生成时间数据
time = np.linspace(0, 0.3, num=100)

plt.plot(time, np.sin(time))
ax = plt.gca()

# 手动设置X轴刻度为0、100e-3、200e-3、300e-3
ax.set_xticks([0, 100e-3, 200e-3, 300e-3])

# 自定义格式化函数,将刻度值转换为1e-3的倍数并显示为科学计数法
def format_x_ticks(value, tick_num):
    scaled_value = value / 1e-3
    return f"{scaled_value:.0f}e-3"

ax.xaxis.set_major_formatter(FuncFormatter(format_x_ticks))

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 14:55:54