CASE6.1
设置坐标轴范围与刻度
通过 set_xlim / set_ylim 控制显示区间,使用 MultipleLocator 与 FormatStrFormatter统一刻度间隔和小数位数,得到规整的坐标网格。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
x = np.linspace(0, 12, 100)
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(x, np.sin(x), color='#16243A', linewidth=2)
# 限定范围
ax.set_xlim(0, 12)
ax.set_ylim(-1.4, 1.4)
# 统一刻度间隔与格式
ax.xaxis.set_major_locator(MultipleLocator(2))
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
plt.tight_layout()
plt.show()