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 设置y轴刻度标记的小数点数目+设置科学计数法标记_第1张图片
参考链接:matplotlib.ticker — Matplotlib 3.7.2 documentation
matplotlib 设置y轴刻度标记的小数点数目+设置科学计数法标记_第2张图片

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()

matplotlib 设置y轴刻度标记的小数点数目+设置科学计数法标记_第3张图片
上述代码中的set_powerlimits()能够设置科学计数法的范围
matplotlib 设置y轴刻度标记的小数点数目+设置科学计数法标记_第4张图片
如果设置formatter.set_powerlimits((-2, 2)) , 只有小于等于0.01或者大于等于100才会按照科学计数法

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

参考链接:matplotlib.ticker — Matplotlib 3.7.2 documentation
matplotlib 设置y轴刻度标记的小数点数目+设置科学计数法标记_第5张图片

你可能感兴趣的:(Python,matplotlib,python)