今天通过过一个简单的实列,简单说明如何控制坐标轴上的主、副刻度线的参数:宽度、高度、方向、间隔。
全部代码在文末。
1:导入我们所需要的库
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import MultipleLocator# MultipleLocator用于调整刻度线的间隔
更多MultipleLocator参数
2:创建数据并建立绘图区
x = np.arange(1, 10)y1 = x ** 2y2 = np.array([2, 6, 15, 18, 25, 70, 40, 70, 90])# 创建画布plt.figure(figsize=(8, 6))plt.rcParams["figure.dpi"] = 300# 分辨率# 建立坐标系axes = plt.subplot()
3:调整主、副刻度参数
axes.minorticks_on()# 显示副刻度线axes.tick_params(axis="both", which="major", direction="in", width=1, length=5)axes.tick_params(axis="both", which="minor", direction="in", width=1, length=3)# 设置主、副刻度线参数axes.xaxis.set_minor_locator(MultipleLocator(0.4))# 设置 X 轴上的副刻度线之间的间隔为0.4
axes.tick_params中参数含义:
axis:修改的对象,可选 “X”,“Y”,“both”;
which:“major”主刻度线;“minor”副刻度线;
direction:刻度线的方向;
width、length:宽度、长度
4:绘图
plt.plot(x, y1, color="k")plt.plot(x, y2, marker="o", linestyle="none", color="k")plt.axis([0, 10, 0, 100])# x,y轴最大最小值# grid 设置网格线性plt.grid(True, which="major", linestyle="--", color="gray", linewidth=0.75)plt.grid(True, which="minor", linestyle=":", color="lightgray", linewidth=0.75)plt.xlabel(r"$\alpha^2+\beta^2$")plt.ylabel(r"$V_a (m/s)$")plt.legend(["Calculate", "Experiment"])plt.show()
其中:
$\alpha^2+\beta^2$
$V_a (m/s)$
是LaTex编码下的公式。
5:结果
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import MultipleLocatorx = np.arange(1, 10)y1 = x ** 2y2 = np.array([2, 6, 15, 18, 25, 70, 40, 70, 90])plt.figure(figsize=(8, 6))plt.rcParams["figure.dpi"] = 300# 分辨率axes = plt.subplot()axes.minorticks_on()axes.tick_params(axis="both", which="major", direction="in", width=1, length=5)axes.tick_params(axis="both", which="minor", direction="in", width=1, length=3)axes.xaxis.set_minor_locator(MultipleLocator(0.4))plt.plot(x, y1, color="k")plt.plot(x, y2, marker="o", linestyle="none", color="k")plt.axis([0, 10, 0, 100])plt.grid(True, which="major", linestyle="--", color="gray", linewidth=0.75)plt.grid(True, which="minor", linestyle=":", color="lightgray", linewidth=0.75)plt.xlabel(r"$\alpha^2+\beta^2$")plt.ylabel(r"$V_a (m/s)$")plt.legend(["Calculate", "Experiment"])plt.show()