刻度由刻度标签和刻度线组成,如果需要进一步设置刻度样式,就需要用到定位器和刻度格式器。
刻度定位器用来设置刻度线的位置,刻度格式器用来设置刻度标签的显示样式。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FuncFormatter
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['font.serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题,或者转换负号为字符串
x = np.linspace(0.5, 3.5, 100)
y = np.sin(x)
# 创建画布
fig = plt.figure(figsize=(8, 8))
# 添加子图,这里 111 表示就一张图,返回该子图的坐标系对象
axes = fig.add_subplot(111)
# 设置坐标轴的主刻度线
axes.xaxis.set_major_locator(MultipleLocator(2.0)) # 2的倍数显示主刻度线
axes.yaxis.set_major_locator(MultipleLocator(1.0)) # 1的倍数显示主刻度线
# 设置坐标轴主刻度线之间的辅助刻度线
axes.xaxis.set_minor_locator(AutoMinorLocator(4)) # 每个主刻度线间等分8段
axes.yaxis.set_minor_locator(AutoMinorLocator(4)) # 每个主刻度线间等分4段
# 定义修改刻度标签格式的函数,这里有要求参数必须是x和pos
def minor(x, pos):
return f"{x:.2f}"
def major(x, pos):
return f"{x:.1f}"
# 将之前定义的函数传入格式
axes.xaxis.set_major_formatter(FuncFormatter(major))
axes.yaxis.set_major_formatter(FuncFormatter(major))
axes.xaxis.set_minor_formatter(FuncFormatter(minor))
axes.yaxis.set_minor_formatter(FuncFormatter(minor))
# 设置刻度线和刻度标签的样式
axes.tick_params(axis="x", which="major", length=15, width=2.0, colors="r")
axes.tick_params(axis="y", which="minor", length=5, width=1.0, labelsize=10, labelcolor="0.25")
# 设置要显示的坐标范围
axes.set_xlim(0, 4)
axes.set_ylim(0, 2)
# 用该子图的坐标系对象实例画图
axes.plot(x, y, c=(0.25, 0.25, 1.00), lw=2, zorder=10)
# axes.plot(x, y, c=(0.25, 0.25, 1.00), lw=2, zorder=0)
# 设置网格线
axes.grid(linestyle="-", linewidth=0.5, color="r", zorder=0)
# 显示画布
plt.show()
最终结果如图: