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()
Reference link : matplotlib.ticker — Matplotlib 3.7.2 documentation
2 Set the y-axis tick mark scientific notation representation
Use ScalarFormatter
scientific 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()
In the above code, set_powerlimits()
the range of scientific notation can be set .
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