matplotlib 设置y轴刻度标记的小数点数目+设置科学计数法标记

1 设置y轴刻度标记的小数点数目

使用FormatStrFormatter,通过使用格式字符串'%1.2f'来设置坐标轴刻度标签保留两位小数。

'%1.2f'格式字符串指定刻度标签以浮点数形式显示,并保留两位小数。

import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

# 创建画布和子图
fig, ax = plt.subplots()

# 绘制图形
x = [1, 2, 3, 4, 5]
y = [1.2345, 2.3456, 3.4567, 4.5678, 5.6789]
ax.plot(x, y)

# 设置y轴刻度标签保留两位小数
y_formatter = FormatStrFormatter('%1.2f')
ax.yaxis.set_major_formatter(y_formatter)

# 展示图形
plt.show()

在这里插入图片描述
参考链接matplotlib.ticker — Matplotlib 3.7.2 documentation
在这里插入图片描述

2 设置y轴刻度线标记科学计数法表示

使用ScalarFormatter通过科学计数法设置y轴刻度标记的小数点数目

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

# 创建画布和子图
fig, ax = plt.subplots()

# 绘制图形
x = [1, 2, 3, 4, 5]
y = [1234, 5678, 9876, 2345, 8765]
ax.plot(x, y)

# 将useMathText设置为True,使得刻度标记显示为科学计数法
y_formatter = ScalarFormatter(useMathText=True)
# 控制刻度标记的科学计数法显示
y_formatter.set_powerlimits((-2, 2))  
ax.yaxis.set_major_formatter(y_formatter)

# 展示图形
plt.show()

在这里插入图片描述
上述代码中的set_powerlimits()能够设置科学计数法的范围
在这里插入图片描述
如果设置formatter.set_powerlimits((-2, 2)) , 只有小于等于0.01或者大于等于100才会按照科学计数法

99 还是99,但100表示为1×10^-2

参考链接matplotlib.ticker — Matplotlib 3.7.2 documentation
在这里插入图片描述

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值