笔记 / Matplotlib 数据可视化备忘速查 · 更新于 2026-10-15

Matplotlib 数据可视化备忘速查

适用环境:Windows 11 / Python 3.12 / Matplotlib 3.11 / NumPy 2.5 / Pandas 3.0
面向对象写法 (fig, ax = plt.subplots()) 更专业可控。


1. 环境与中文乱码防御(必写头)

import matplotlib.pyplot as plt
import numpy as np

# 解决 Win11 中文方块 + 负号乱码
plt.rcParams['font.sans-serif'] = ['SimHei']      # 黑体
plt.rcParams['axes.unicode_minus'] = False        # 正常显示负号

安装(清华源):

pip install matplotlib numpy pandas -i https://pypi.tuna.tsinghua.edu.cn/simple

2. 核心组成模型

层级 说明
Figure 画布(最外层容器)
Axes 坐标系(一个 Figure 可包含多个 Axes)
Axis 坐标轴(X/Y轴,含刻度、标签)
Tick 刻度(主/副刻度,标签)

3. 创建画布与坐标轴

plt.figure() 常用参数

参数 说明
figsize=(w, h) 宽×高(英寸)
dpi 分辨率(默认100,打印用300)
facecolor 背景色(如 '#f5f5f5')
edgecolor 边框颜色

add_axes() 手动定位(归一化坐标 [left, bottom, width, height])

fig = plt.figure(figsize=(8,5))
ax_main = fig.add_axes([0.1, 0.1, 0.8, 0.8])      # 主图
ax_inset = fig.add_axes([0.55, 0.55, 0.3, 0.3])  # 嵌入小图

subplots() 快速多子图

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))
axes[0,0].plot(...)   # 左上
axes[0,1].bar(...)    # 右上
# 自动调整间距
plt.tight_layout()

4. 常见图表 API

折线图 plot()

ax.plot(x, y, 
        color='#1f77b4', linestyle='--', linewidth=2,
        marker='o', markersize=8, 
        markerfacecolor='white', markeredgecolor='red',
        label='图例名')

常用线型:'-' 实线, '--' 虚线, '-.' 点划线, ':' 点线
常用标记:'o' 圆, 's' 方, '^' 三角, '*' 星, 'D' 菱形

柱状图 bar() / barh()

ax.bar(x, height, width=0.8, color='blue', edgecolor='black', alpha=0.85, label='')
# 横向条形图:ax.barh(y, width, ...)

散点图 scatter()

ax.scatter(x, y, 
           s=size_array,           # 点大小(可映射)
           c=color_array,          # 点颜色(可映射)
           alpha=0.6, edgecolors='red', linewidth=1.5)

直方图 hist()

n, bins, patches = ax.hist(x, bins=10, density=False, 
                           color='#1f77b4', edgecolor='white', alpha=0.85)
# density=True 转为概率密度;cumulative=True 累积直方图

饼图 pie()

ax.pie(x, labels=labels, autopct='%1.1f%%', startangle=90,
       explode=[0.1,0,0,...], shadow=True,
       wedgeprops=dict(width=0.4, edgecolor='white'))  # width<1 变环形图

5. 绘图修饰与美化(常用方法)

操作 方法(pyplot风格) 面向对象等价
主标题 plt.title('text', fontsize=14, pad=20) ax.set_title(...)
X轴标签 plt.xlabel('text', fontsize=12, labelpad=10) ax.set_xlabel(...)
Y轴标签 plt.ylabel('text', ...) ax.set_ylabel(...)
网格 plt.grid(True, axis='y', linestyle='--', alpha=0.7, color='#ccc') ax.grid(...)
坐标轴范围 plt.xlim(0, 10); plt.ylim(0, 100) ax.set_xlim(); ax.set_ylim()
刻度自定义 plt.xticks(ticks, labels, rotation=45) ax.set_xticks(); ax.set_xticklabels()
图例 plt.legend(loc='best', frameon=True, shadow=True, ncol=2) ax.legend(...)
数据标签 plt.text(x, y, 'text', ha='center', va='bottom') ax.text(...)
自动边距 plt.tight_layout() fig.tight_layout()

常用 loc 值:'upper left', 'upper right', 'lower left', 'lower right', 'center', 'best'


6. 双坐标轴(Twin Axes)

双Y轴(共享X轴)

fig, ax1 = plt.subplots(figsize=(10,5))
ax1.bar(x, data1, color='blue', label='...')
ax1.set_ylabel('左侧单位', color='blue')
ax1.tick_params(axis='y', labelcolor='blue')

ax2 = ax1.twinx()
ax2.plot(x, data2, color='red', marker='o', label='...')
ax2.set_ylabel('右侧单位', color='red')
ax2.tick_params(axis='y', labelcolor='red')

双X轴(共享Y轴)类似,使用 twiny()


7. 子图布局与间距

fig, axes = plt.subplots(2, 3, figsize=(12, 6))   # 2行3列
# axes 是二维数组,按 [row, col] 索引
fig.tight_layout()   # 自动防重叠
# 或手动调整:plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1, wspace=0.3, hspace=0.3)

8. 保存与读取图片

保存 savefig(必须在 show() 之前)

plt.savefig('output.png', dpi=300, bbox_inches='tight', transparent=False)

读取 imread → NumPy 数组

img = plt.imread('image.png')   # 形状 (H, W, 3) 或 (H, W, 4) 含透明度
plt.imshow(img)
plt.axis('off')

9. 图像通道操作(遮罩 / 灰度)

添加矩形半透明遮罩(直接修改NumPy数组)

h, w, _ = img.shape
img[int(h*0.2):int(h*0.4), :, 0] = 1.0   # R通道全1(红色)
img[... , 1] = 0.5                       # G通道减半
plt.imshow(img)

RGB → 灰度(加权平均)

gray = np.dot(img[..., :3], [0.2989, 0.5870, 0.1140])
plt.imshow(gray, cmap='gray')

10. 典型案例片段索引


11. 常见错误

问题 解决方案
中文方块 设置 rcParams['font.sans-serif'] = ['SimHei']
负号显示为方块 rcParams['axes.unicode_minus'] = False
savefig 保存空白 放在 plt.show() 之前
子图标签重叠 调用 plt.tight_layout()
图像遮罩不生效 确保操作的是副本 img = plt.imread(...).copy()
NumPy 2.x 类型别名 直接用 np.float64 / np.int64,不用过时别名