Matplotlib Pyplot 模块详解(完整教程)
pyplot 是 Matplotlib 的核心子模块,提供了 类 MATLAB 风格的绘图接口,让绘图变得简单直观。本教程带你全面掌握 pyplot 的使用。
一、pyplot 是什么?
import matplotlib.pyplot as plt
plt是matplotlib.pyplot的标准别名- 提供 状态机(state-based) 绘图方式:自动管理当前图表(
figure)和坐标轴(axes) - 适合 快速绘图、探索性分析
对比:
plt.plot()是简易方式;fig, ax = plt.subplots()是面向对象方式(推荐用于复杂图)
二、核心概念
| 概念 | 说明 |
|---|---|
Figure | 整个画布(窗口) |
Axes | 坐标轴区域(一个 Figure 可包含多个 Axes) |
Axis | 坐标轴(X轴、Y轴) |
Artist | 所有可见元素(线、文本、图例等) |
plt.figure() # 创建画布
plt.plot() # 在当前 Axes 上绘图
plt.show() # 显示图像
三、基本绘图函数(必会)
1. plt.plot() – 折线图
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()
样式参数(格式字符串)
plt.plot(x, y, 'ro--') # 红圈 + 虚线
# 格式: [color][marker][line]
# 示例:
# 'b-' 蓝色实线
# 'g^:' 绿色三角 + 点线
# 'm--' 品红虚线
详细参数
plt.plot(x, y,
color='red', # 颜色
linewidth=2, # 线宽
linestyle='-.', # 线型
marker='o', # 标记
markersize=6, # 标记大小
markerfacecolor='yellow',
markeredgecolor='black',
label='sin(x)', # 图例标签
alpha=0.8) # 透明度
2. plt.scatter() – 散点图
plt.scatter(x, y, c='blue', s=50, alpha=0.6)
# c: 颜色, s: 大小, alpha: 透明度
颜色映射:
plt.scatter(x, y, c=y, cmap='viridis', s=60)
plt.colorbar() # 显示颜色条
3. plt.bar() / plt.barh() – 柱状图
categories = ['A', 'B', 'C']
values = [3, 7, 5]
plt.bar(categories, values, color=['red', 'green', 'blue'])
plt.show()
水平柱状图:
plt.barh(categories, values)
4. plt.hist() – 直方图
data = np.random.randn(1000)
plt.hist(data, bins=30, color='skyblue', edgecolor='black', alpha=0.7)
plt.show()
5. plt.pie() – 饼图
sizes = [30, 20, 25, 25]
labels = ['苹果', '香蕉', '橙子', '葡萄']
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.axis('equal') # 正圆
plt.show()
6. plt.imshow() – 图像显示
img = np.random.rand(10, 10)
plt.imshow(img, cmap='hot')
plt.colorbar()
plt.show()
四、图表美化(必须掌握)
| 函数 | 用途 |
|---|---|
plt.title() | 设置标题 |
plt.xlabel() / plt.ylabel() | 坐标轴标签 |
plt.xlim() / plt.ylim() | 坐标轴范围 |
plt.grid() | 显示网格 |
plt.legend() | 显示图例 |
plt.text(x, y, '文字') | 添加文本 |
plt.annotate() | 添加带箭头注释 |
plt.plot(x, np.sin(x), label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
plt.title('正弦与余弦函数', fontsize=16, fontweight='bold')
plt.xlabel('x 值')
plt.ylabel('y 值')
plt.grid(True, alpha=0.3)
plt.legend(loc='upper right')
plt.xlim(0, 10)
plt.ylim(-1.5, 1.5)
plt.show()
五、多图布局(子图)
方法1:plt.subplot()(快速)
plt.figure(figsize=(10, 6))
plt.subplot(2, 2, 1) # 2行2列,第1个
plt.plot(x, np.sin(x))
plt.title('sin(x)')
plt.subplot(2, 2, 2)
plt.plot(x, np.cos(x))
plt.title('cos(x)')
plt.subplot(2, 2, 3)
plt.plot(x, x**2)
plt.title('x²')
plt.subplot(2, 2, 4)
plt.hist(np.random.randn(1000), bins=20)
plt.title('直方图')
plt.tight_layout() # 自动调整间距
plt.show()
方法2:plt.subplots()(推荐,面向对象)
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title('sin(x)')
axes[0, 1].plot(x, np.cos(x))
axes[0, 1].set_title('cos(x)')
axes[1, 0].scatter(x, np.sin(x))
axes[1, 0].set_title('散点')
axes[1, 1].bar(['A','B','C'], [3,7,5])
axes[1, 1].set_title('柱状图')
plt.tight_layout()
plt.show()
六、保存图像
plt.plot(x, np.sin(x))
plt.title('保存的图像')
plt.savefig('sin_wave.png', dpi=300, bbox_inches='tight', facecolor='white')
# 支持格式:png, jpg, pdf, svg, eps
七、交互式设置
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS'] # 中文
plt.rcParams['axes.unicode_minus'] = False # 负号正常显示
plt.rcParams['figure.figsize'] = (8, 6) # 默认画布大小
plt.rcParams['axes.grid'] = True # 默认网格
plt.rcParams['legend.loc'] = 'best' # 图例位置
八、完整示例:专业级图表
import matplotlib.pyplot as plt
import numpy as np
# 数据
x = np.linspace(0, 2*np.pi, 100)
y1, y2 = np.sin(x), np.cos(x)
# 样式设置
plt.style.use('seaborn-v0_8')
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 创建画布
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))
# 左图:折线 + 填充
ax1.plot(x, y1, 'b-', label='sin(x)', linewidth=2)
ax1.plot(x, y2, 'r--', label='cos(x)', linewidth=2)
ax1.fill_between(x, y1, alpha=0.2, color='blue')
ax1.set_title('正弦与余弦函数', fontsize=14, fontweight='bold')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.grid(True, alpha=0.3)
ax1.legend()
# 右图:散点 + 颜色映射
sc = ax2.scatter(x, y1, c=y2, cmap='plasma', s=50, edgecolors='k')
ax2.set_title('散点图(颜色表示 cos 值)')
ax2.set_xlabel('x')
ax2.set_ylabel('sin(x)')
plt.colorbar(sc, ax=ax2, label='cos(x)')
# 布局与保存
plt.suptitle('Matplotlib Pyplot 综合示例', fontsize=16)
plt.tight_layout()
plt.savefig('pyplot_demo.png', dpi=200, bbox_inches='tight')
plt.show()
九、Pyplot vs 面向对象(OO)对比
| 方式 | 代码 | 适用场景 |
|---|---|---|
| Pyplot | plt.plot() | 快速绘图、教学、交互 |
| OO 风格 | ax.plot() | 复杂图表、多子图、生产代码 |
# Pyplot 风格
plt.plot(x, y)
plt.title('标题')
# OO 风格(推荐)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('标题')
plt.show()
十、常用 pyplot 函数速查表
| 函数 | 用途 |
|---|---|
plt.plot() | 折线图 |
plt.scatter() | 散点图 |
plt.bar() | 垂直柱状图 |
plt.barh() | 水平柱状图 |
plt.hist() | 直方图 |
plt.pie() | 饼图 |
plt.imshow() | 图像 |
plt.contour() | 等高线图 |
plt.quiver() | 矢量场 |
plt.errorbar() | 误差线 |
plt.boxplot() | 箱线图 |
plt.violinplot() | 小提琴图 |
官方文档
- Pyplot 教程:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html
- 示例图库:https://matplotlib.org/stable/gallery/index.html
现在开始练习!
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,2,8], 'go-')
plt.title('快速上手 Pyplot')
plt.show()
需要我为你生成:
- 交互式 Jupyter Notebook 模板?
- 特定图表(如热力图、3D图)的 pyplot 代码?
- 中文支持配置脚本?
告诉我你的需求!