matplotlib sets the number of decimal points for y-axis scale marks + sets scientific notation marks

1 Set the number of decimal points for the y-axis tick marks

Use FormatStrFormatter, by using a format string '%1.2f'to set the axis tick labels to two decimal places.

'%1.2f'The format string specifies that tick labels are displayed as floating point numbers with two decimal places.

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

insert image description here
Reference link : matplotlib.ticker — Matplotlib 3.7.2 documentation
insert image description here

2 Set the y-axis tick mark scientific notation representation

Use ScalarFormatterscientific notation to set the number of decimal points for y-axis tick marks

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

insert image description here
In the above code, set_powerlimits()the range of scientific notation can be set .
insert image description here
If set formatter.set_powerlimits((-2, 2)),Only less than or equal to 0.01 or greater than or equal to 100 will use scientific notation

99 is still 99, but 100 is expressed as 1×10^-2

Reference link : matplotlib.ticker — Matplotlib 3.7.2 documentation
insert image description here

Guess you like

Origin blog.csdn.net/weixin_45913084/article/details/132080283