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

matplotlib如何设置ax1的y轴缩放规则与ax2一致,显示1e-6在y轴顶部

要实现两个子图y轴格式统一、固定缩放基准并将缩放系数显示在y轴顶部,可以通过Matplotlib的ScalarFormatter强制指定刻度的科学计数指数,具体修改后的代码如下:

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

fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
x = np.linspace(0, 1000, 3)
y1 = np.full_like(x, 4e-6)
y2 = np.full_like(x, 4e-7)

ax1.plot(x, y1)
ax2.plot(x, y2)

# 配置ax1的y轴格式化规则
y_formatter = ScalarFormatter(useMathText=True)
# 强制y轴固定以1e-6为缩放基准
y_formatter.set_powerlimits((-6, -6))
ax1.yaxis.set_major_formatter(y_formatter)
# 将缩放系数调整到y轴顶部显示
ax1.yaxis.offsetText.set_verticalalignment('bottom')
ax1.yaxis.offsetText.set_horizontalalignment('right')

plt.show()

运行代码后,ax1的y轴刻度会显示为0~4的整数,顶部显示×10⁻⁶的缩放系数,和ax2的显示格式完全对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:09:03