Python Matplotlib核心概念
原创

Python

Python Matplotlib核心概念

发表于 2026-11-26

更新于 11小时前

阅读量: 9

学习笔记说明

这是一篇Python的学习笔记,关于Python Matplotlib核心概念,仅做记录

Matplotlib核心概念

Matplotlib 是整个 Python 数据可视化生态的基石。
无论你用 Seaborn、Plotly 还是其他高级库,底层都离不开 Matplotlib 的三层架构。

本节课目标:建立 Matplotlib 的概念体系——
搞懂 Figure、Axes、Artist 这三个核心对象及其关系。

!uv add matplotlib ipympl
1
# 启用交互式后端
%matplotlib widget
1
2
import numpy as np
import matplotlib.pyplot as plt

# 设置中文字体支持(可选)
plt.rcParams.update({
    "font.sans-serif":["PingFang SC"],
    "axes.unicode_minus":False,
    "figure.dpi": 100
})
1
2
3
4
5
6
7
8
9

1. Figure — 画布

Figure 是最顶层的容器,相当于一张画布。
一个 Figure 可以包含一个或多个 Axes(绘图区)。

创建 Figure 最标准的方式:

fig, ax = plt.subplots(figsize=(8, 4))  # 一张画布 + 一个绘图区
ax.plot([1, 2, 3], [1, 4, 9], marker="o")
1
2

多个 Axes 的 Figure

fig, axes = plt.subplots(2, 2, figsize=(8,6))

axes[0, 0].plot([1, 2, 3], [1, 4, 9])
axes[0, 1].bar([1, 2, 3], [3, 5, 2])
axes[1, 0].scatter([1, 2, 3], [1, 4, 9])
axes[1, 1].hist(np.random.randn(10000), bins=100)
1
2
3
4
5
6

主题/样式

Figure 可以通过 plt.style.use() 切换整体视觉风格,
影响所有 Axes 的配色、网格、字体等。

print(plt.style.available)
1
plt.style.use('ggplot')
1
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot([1, 2, 3], [1, 4, 9])
ax.bar([1, 2, 3], [3, 5, 2], alpha=0.5)
1
2
3
plt.style.use('default')  # 恢复默认
1

2. Axes — 绘图区

Axes 是 Figure 内部的独立绘图区域,
数据实际被绘制在 Axes 上。
每个 Axes 有自己的坐标空间、坐标轴(Axis)、刻度、标签。

一个常见误区:Axes 不等于 Axis,一个 Axes 通常有 2 个 Axis(x轴、y轴)。

fig, ax = plt.subplots(figsize=(8, 4))

x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x), label='sin')
ax.plot(x, np.cos(x), label='cos')

ax.set_title('三角函数')
ax.set_xlabel('X 轴')
ax.set_ylabel('\n'.join('Y轴'), rotation = 0)
ax.set_xlim(0, 10)
ax.set_ylim(-1.5, 1.5)
ax.legend()
ax.grid(True, linestyle=':', alpha=0.5)
1
2
3
4
5
6
7
8
9
10
11
12
13
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')

# 生成螺旋线数据
t = np.linspace(0, 20, 1000)
x = np.sin(t)
y = np.cos(t)
z = t

# 绘制3D线图
ax.plot(x, y, z, linewidth=2, color='red')

ax.set_xlabel('X轴')
ax.set_ylabel('Y轴')
ax.set_zlabel('Z轴')
ax.set_title('3D螺旋线示例')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Spines(脊线)

Axes 的四条边框线称为 spines。
常见的「干净风格」就是隐藏上、右两条脊线。

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot([1, 2, 3], [1, 4, 9], linewidth=2)

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color('gray')
ax.spines['bottom'].set_linewidth(1.5)
1
2
3
4
5
6
7

注解与图例

fig, ax = plt.subplots(figsize=(8, 4))

x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
ax.plot(x, y, marker='o')

ax.annotate('最大值', xy=(5, 25), xytext=(4, 23),
            arrowprops={
                "arrowstyle": "->",
                "color": "red"
            },
            fontsize=12)
ax.text(1, 20, '二次函数', fontsize=14, style='italic',
        bbox={
            "boxstyle": "round",
            "facecolor": "wheat",
            "alpha": 0.5
        }
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

3. Artist — 绘制元素

Artist 是 Matplotlib 里「一切可见的东西」。
Figure、Axes、Axis、曲线、柱体、文字……都是 Artist。

我们平时画图时,就是在不断创建和配置 Artist 对象。

fig, ax = plt.subplots(figsize=(8, 4))

ax.plot([1, 2, 3], [1, 4, 9], color='royalblue', linewidth=3, label='折线')
ax.bar([4, 5, 6], [3, 7, 5], color='tomato', edgecolor='black', alpha=0.7, label='柱状图')
ax.scatter([7, 8, 9], [8, 2, 6], color='green', s=100, label='散点')

ax.legend()
1
2
3
4
5
6
7

每个 Artist 都可以单独修改属性:

总结:三层架构

Figure(画布)
  ├── Axes(绘图区1)
  │     ├── Axis(X轴)
  │     ├── Axis(Y轴)
  │     ├── Line2D(折线)
  │     ├── Rectangle(柱体)
  │     ├── Text(文字)
  │     ├── Legend(图例)
  │     └── ...
  ├── Axes(绘图区2)
  │     └── ...
  └── ...
1
2
3
4
5
6
7
8
9
10
11
12
评论
0/100
0/100
0/100
0/250
暂无评论