Matplotlib 画图技巧大全

2026-06-28 · 阅读 12 分钟 · 机器学习可视化

← 返回首页

Matplotlib 简介

Matplotlib 是 Python 中最基础、最强大的可视化库。它提供了类似 MATLAB 的绘图接口,支持多种图表类型,是数据可视化的基石。

安装与基础设置

pip install matplotlib

import matplotlib.pyplot as plt
import numpy as np

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS']
plt.rcParams['axes.unicode_minus'] = False

# 设置图表风格
plt.style.use('seaborn-v0_8')

基础图表

折线图

# 基础折线图
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(10, 6))
plt.plot(x, y, label='sin(x)', color='blue', linewidth=2)
plt.plot(x, np.cos(x), label='cos(x)', color='red', linewidth=2, linestyle='--')
plt.xlabel('X 轴')
plt.ylabel('Y 轴')
plt.title('三角函数图')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

柱状图

# 基础柱状图
categories = ['A', 'B', 'C', 'D', 'E']
values = [23, 45, 56, 78, 32]

plt.figure(figsize=(8, 5))
plt.bar(categories, values, color=['#3498db', '#2ecc71', '#e74c3c', '#f39c12', '#9b59b6'])
plt.xlabel('类别')
plt.ylabel('数值')
plt.title('柱状图示例')
plt.show()

# 水平柱状图
plt.figure(figsize=(8, 5))
plt.barh(categories, values, color='#3498db')
plt.xlabel('数值')
plt.ylabel('类别')
plt.title('水平柱状图')
plt.show()

散点图

# 散点图
np.random.seed(42)
x = np.random.randn(100)
y = 2 * x + np.random.randn(100)
colors = np.random.rand(100)
sizes = np.random.rand(100) * 100

plt.figure(figsize=(10, 6))
scatter = plt.scatter(x, y, c=colors, s=sizes, alpha=0.6, cmap='viridis')
plt.colorbar(scatter)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('散点图示例')
plt.show()

饼图

# 饼图
labels = ['Python', 'Java', 'C++', 'JavaScript', 'Other']
sizes = [35, 25, 20, 15, 5]
colors = ['#3498db', '#e74c3c', '#2ecc71', '#f39c12', '#9b59b6']
explode = (0.1, 0, 0, 0, 0)

plt.figure(figsize=(8, 8))
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)
plt.title('编程语言使用比例')
plt.axis('equal')
plt.show()

高级图表

子图布局

# 创建 2x2 子图
fig, axes = plt.subplots(2, 2, figsize=(12, 10))

# 子图1: 折线图
axes[0, 0].plot(x, np.sin(x), 'b-')
axes[0, 0].set_title('正弦函数')

# 子图2: 柱状图
axes[0, 1].bar(categories, values, color='green')
axes[0, 1].set_title('柱状图')

# 子图3: 散点图
axes[1, 0].scatter(np.random.randn(50), np.random.randn(50), c='red', alpha=0.5)
axes[1, 0].set_title('散点图')

# 子图4: 饼图
axes[1, 1].pie(sizes, labels=labels, autopct='%1.1f%%')
axes[1, 1].set_title('饼图')

plt.tight_layout()
plt.show()

3D 图表

from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# 生成数据
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# 绘制曲面图
surf = ax.plot_surface(X, Y, Z, cmap='viridis')
fig.colorbar(surf)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D 曲面图')
plt.show()

机器学习可视化案例

混淆矩阵

from sklearn.metrics import confusion_matrix
import seaborn as sns

# 假设 y_true 和 y_pred 是真实标签和预测标签
cm = confusion_matrix(y_true, y_pred)

plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.xlabel('预测标签')
plt.ylabel('真实标签')
plt.title('混淆矩阵')
plt.show()

ROC 曲线

from sklearn.metrics import roc_curve, auc

fpr, tpr, _ = roc_curve(y_true, y_scores)
roc_auc = auc(fpr, tpr)

plt.figure(figsize=(8, 6))
plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC 曲线 (AUC = {roc_auc:.2f})')
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('假正率')
plt.ylabel('真正率')
plt.title('ROC 曲线')
plt.legend(loc="lower right")
plt.show()

特征重要性

from sklearn.ensemble import RandomForestClassifier

# 训练模型
model = RandomForestClassifier()
model.fit(X_train, y_train)

# 获取特征重要性
importance = model.feature_importances_
feature_names = X.columns

# 绘制特征重要性图
plt.figure(figsize=(10, 6))
plt.barh(feature_names, importance, color='steelblue')
plt.xlabel('重要性')
plt.ylabel('特征')
plt.title('特征重要性排名')
plt.tight_layout()
plt.show()

保存图表

# 保存为 PNG 文件
plt.savefig('figure.png', dpi=300, bbox_inches='tight')

# 保存为 PDF 文件
plt.savefig('figure.pdf', bbox_inches='tight')

# 保存为 SVG 文件(矢量图,可无限缩放)
plt.savefig('figure.svg', bbox_inches='tight')
小贴士: 使用 plt.style.use() 可以快速切换图表风格,推荐使用 'seaborn-v0_8' 或 'ggplot' 风格。

总结

Matplotlib 是数据可视化的基础,掌握它将为学习其他可视化库(如 Seaborn、Plotly)打下坚实基础。多实践、多尝试不同的图表类型,你会发现数据可视化的乐趣。