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

如何强制Matplotlib为坐标轴数值启用科学计数法?

强制Matplotlib坐标轴显示科学计数法

要让Matplotlib的坐标轴(比如你的y轴)不管数值大小都强制显示科学计数法,有两种实用的实现方式:

方法一:直接调用ticklabel_format

在绘图代码中添加一行配置,指定y轴启用科学计数法且不受数值范围限制:

plt.figure()
BarNames = ['SVR', 'LSTM', 'GRU', 'CNN']
colours = ['orange', 'green', 'darkred', 'purple']
values = [9.931470649536813e-04, 9.433767714089219e-04, 8.682655450180871e-04, 5.461618193308908e-04]
plt.bar(BarNames, values, color=colours)
plt.xlabel('CincoCrypto Models')
plt.ylabel('Mean Absolute Percentage Error (%)')

# 强制y轴显示科学计数法
plt.ticklabel_format(axis='y', style='sci', scilimits=(0,0))

plt.savefig(f"{cryptos[2]}_MAPE", dpi=300, bbox_inches='tight')

参数说明:

  • axis='y':指定对y轴生效
  • style='sci':设置为科学计数法风格
  • scilimits=(0,0):表示无论数值的数量级如何,都强制启用科学计数法

方法二:使用ticker模块精细控制

如果需要更灵活的自定义配置,可以借助matplotlib.ticker模块的ScalarFormatter:

import matplotlib.ticker as ticker

plt.figure()
BarNames = ['SVR', 'LSTM', 'GRU', 'CNN']
colours = ['orange', 'green', 'darkred', 'purple']
values = [9.931470649536813e-04, 9.433767714089219e-04, 8.682655450180871e-04, 5.461618193308908e-04]
plt.bar(BarNames, values, color=colours)
plt.xlabel('CincoCrypto Models')
plt.ylabel('Mean Absolute Percentage Error (%)')

# 获取y轴对象并设置格式化规则
ax = plt.gca()
formatter = ticker.ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((0, 0))
ax.yaxis.set_major_formatter(formatter)

plt.savefig(f"{cryptos[2]}_MAPE", dpi=300, bbox_inches='tight')

通过上述任意一种方法,你的y轴都会像示例图那样,强制显示科学计数法,同时在轴的末尾标注对应的幂次(比如1e-4)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:00:14