01 基础绘图框架
推荐使用面向对象接口 fig, ax = plt.subplots()。
当一个页面中存在多个子图,或者需要对坐标轴进行精确控制时,这种写法更加清晰。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x)
fig, ax = plt.subplots(figsize=(7, 4.5), dpi=150)
ax.plot(
x, y,
color="tab:blue",
linewidth=1.8,
linestyle="-",
marker="o",
markersize=4,
markevery=30,
label="sin(x)"
)
ax.set_xlabel("x")
ax.set_ylabel("sin(x)")
ax.set_title("Basic Matplotlib Plot")
ax.legend()
ax.grid(True, alpha=0.25)
fig.tight_layout()
plt.show()
02 全局字体与字号
全局样式建议在绘图开始前通过 plt.rcParams 统一设置。
中文环境下可将 font.sans-serif 替换为系统中实际存在的中文字体。
import matplotlib.pyplot as plt
plt.rcParams.update({
# 字体族
"font.family": "DejaVu Sans",
# 中文字体示例:
# "font.sans-serif": ["SimHei", "Microsoft YaHei"],
# 数学公式字体
"mathtext.fontset": "stix",
# 全局字号
"font.size": 11,
"axes.titlesize": 14,
"axes.labelsize": 12,
"xtick.labelsize": 10,
"ytick.labelsize": 10,
"legend.fontsize": 10,
# 负号正常显示
"axes.unicode_minus": False,
})
表 1. 常用字体相关 rcParams
| 参数 | 作用 | 示例 |
|---|---|---|
font.family |
默认字体族 | "DejaVu Sans" |
font.size |
全局基础字号 | 11 |
axes.titlesize |
坐标轴标题字号 | 14 |
axes.labelsize |
x、y 轴标签字号 | 12 |
xtick.labelsize |
x 轴刻度字号 | 10 |
ytick.labelsize |
y 轴刻度字号 | 10 |
03 坐标轴标题与刻度
labelpad 控制坐标轴标签与坐标轴之间的距离,
tick_params 可以统一控制刻度方向、长度、宽度和颜色。
fig, ax = plt.subplots()
ax.plot(x, y)
# 坐标轴标签
ax.set_xlabel("Time / s", labelpad=8, fontsize=12)
ax.set_ylabel("Amplitude", labelpad=8, fontsize=12)
# 坐标轴标题
ax.set_title(
"Signal Response",
fontsize=14,
fontweight="bold",
pad=12
)
# 刻度参数
ax.tick_params(
axis="both", # "x"、"y" 或 "both"
which="major", # "major"、"minor" 或 "both"
direction="in", # "in"、"out"、"inout"
length=5,
width=1.0,
colors="black",
labelsize=10,
top=True,
right=True
)
# 开启次刻度
ax.minorticks_on()
表 2. tick_params 常用参数
| 参数 | 含义 | 常用值 |
|---|---|---|
axis |
设置哪个方向的刻度 | "x"、"y"、"both" |
which |
主刻度或次刻度 | "major"、"minor"、"both" |
direction |
刻度朝向 | "in"、"out"、"inout" |
length |
刻度线长度 | 4、5、6 |
width |
刻度线宽度 | 0.8、1.0 |
top/right |
是否显示顶部或右侧刻度 | True / False |
论文风格中常见设置为
direction="in",并配合
top=True, right=True,使刻度线朝图内延伸。
04 颜色设置
Matplotlib 支持颜色名称、十六进制颜色、RGB 元组、灰度字符串和内