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

Matplotlib散点图轴值为指数形式,如何改为常规数值?

解决Matplotlib坐标轴指数显示问题

方法一:直接关闭科学计数法

使用plt.ticklabel_format()设置style='plain',可快速关闭坐标轴的指数显示,切换为常规数字格式,还能指定作用于X轴、Y轴或双轴。

修改后的完整代码:

import numpy as np
import matplotlib.pyplot as plt

y_test = np.array(y_test)
y_pred = np.array(y_pred)

plt.scatter(y_test, y_pred, color='red')
plt.xlabel('Actual Values')
plt.ylabel('Prediction Values')
plt.title('Actual vs Predicted')

# 关闭科学计数法,应用于双轴
plt.ticklabel_format(style='plain', axis='both')

plt.show()
  • 参数axis可选值:'x'(仅X轴)、'y'(仅Y轴)、'both'(双轴)。

方法二:自定义坐标轴格式(灵活控制显示)

如果需要精确控制显示格式(比如强制整数、保留指定小数位数),可以用FuncFormatter自定义格式化逻辑。

示例1:显示为整数

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

y_test = np.array(y_test)
y_pred = np.array(y_pred)

plt.scatter(y_test, y_pred, color='red')
plt.xlabel('Actual Values')
plt.ylabel('Prediction Values')
plt.title('Actual vs Predicted')

# 定义整数格式化函数
int_formatter = FuncFormatter(lambda x, pos: f'{int(x)}')
# 应用到X轴和Y轴
plt.gca().xaxis.set_major_formatter(int_formatter)
plt.gca().yaxis.set_major_formatter(int_formatter)

plt.show()

示例2:显示为指定小数位数的浮点数

若需保留两位小数,修改格式化函数即可:

float_formatter = FuncFormatter(lambda x, pos: f'{x:.2f}')
plt.gca().xaxis.set_major_formatter(float_formatter)
plt.gca().yaxis.set_major_formatter(float_formatter)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:27:30