← 返回首页
🤖

Matplotlib数据可视化

📂 ai ⏱ 2 min 385 words

Matplotlib数据可视化

数据可视化是数据分析和机器学习中不可或缺的环节。Matplotlib是Python最基础也最灵活的可视化库,理解它能帮助你更好地掌握Seaborn等高级库。

基础折线图

import matplotlib.pyplot as plt
import numpy as np

# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 创建数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 绘制折线图
plt.figure(figsize=(10, 6))
plt.plot(x, y1, label='sin(x)', color='blue', linewidth=2)
plt.plot(x, y2, label='cos(x)', color='red', linestyle='--', linewidth=2)
plt.title('三角函数图像', fontsize=16)
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig('trig_functions.png', dpi=150, bbox_inches='tight')
plt.show()

柱状图

# 柱状图 - 模型性能对比
models = ['线性回归', '随机森林', 'XGBoost', '神经网络']
accuracy = [0.82, 0.89, 0.91, 0.88]
recall = [0.78, 0.85, 0.90, 0.86]

fig, ax = plt.subplots(figsize=(10, 6))
x = np.arange(len(models))
width = 0.35

bars1 = ax.bar(x - width/2, accuracy, width, label='准确率', color='steelblue')
bars2 = ax.bar(x + width/2, recall, width, label='召回率', color='coral')

ax.set_xlabel('模型')
ax.set_ylabel('分数')
ax.set_title('模型性能对比')
ax.set_xticks(x)
ax.set_xticklabels(models)
ax.legend()
ax.set_ylim(0.7, 1.0)

# 添加数值标签
for bar in bars1:
    height = bar.get_height()
    ax.annotate(f'{height:.2f}', xy=(bar.get_x() + bar.get_width()/2, height),
                xytext=(0, 3), textcoords="offset points", ha='center')
plt.show()

散点图

# 散点图 - 特征相关性可视化
np.random.seed(42)
n_samples = 200
feature1 = np.random.randn(n_samples)
feature2 = feature1 * 0.8 + np.random.randn(n_samples) * 0.3
labels = np.random.choice([0, 1], n_samples)

plt.figure(figsize=(8, 6))
colors = ['red' if l == 0 else 'blue' for l in labels]
plt.scatter(feature1, feature2, c=colors, alpha=0.6, edgecolors='w', s=80)
plt.xlabel('特征1')
plt.ylabel('特征2')
plt.title('特征分布散点图')
plt.colorbar(label='类别')
plt.show()

子图布局

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

# 子图1 - 正态分布
axes[0, 0].hist(np.random.randn(1000), bins=30, color='skyblue', edgecolor='black')
axes[0, 0].set_title('正态分布')

# 子图2 - 饼图
sizes = [35, 30, 20, 15]
labels_pie = ['A类', 'B类', 'C类', 'D类']
axes[0, 1].pie(sizes, labels=labels_pie, autopct='%1.1f%%', startangle=90)
axes[0, 1].set_title('数据分布')

# 子图3 - 箱线图
data_box = [np.random.randn(100) + i for i in range(4)]
axes[1, 0].boxplot(data_box, labels=['组1', '组2', '组3', '组4'])
axes[1, 0].set_title('箱线图对比')

# 子图4 - 热力图
corr_matrix = np.random.rand(5, 5)
im = axes[1, 1].imshow(corr_matrix, cmap='YlOrRd')
axes[1, 1].set_title('相关性热力图')
plt.colorbar(im, ax=axes[1, 1])

plt.tight_layout()
plt.savefig('subplots.png', dpi=150)
plt.show()

样式美化

# 查看可用样式
print(plt.style.available)

# 使用预设样式
plt.style.use('seaborn-v0_8-whitegrid')

# 自定义样式
plt.rcParams.update({
    'figure.figsize': (10, 6),
    'font.size': 12,
    'axes.titlesize': 14,
    'axes.labelsize': 12,
    'lines.linewidth': 2,
    'lines.markersize': 8,
})

# 保存自定义样式
plt.savefig('styled_plot.png', dpi=300, bbox_inches='tight',
            facecolor='white', edgecolor='none')

ML可视化实战

# 混淆矩阵可视化
from sklearn.metrics import confusion_matrix
import seaborn as sns

y_true = [0, 1, 1, 0, 1, 0, 1, 1, 0, 0]
y_pred = [0, 1, 0, 0, 1, 0, 1, 0, 1, 0]

cm = confusion_matrix(y_true, y_pred)
plt.figure(figsize=(6, 5))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
            xticklabels=['负类', '正类'],
            yticklabels=['负类', '正类'])
plt.title('混淆矩阵')
plt.ylabel('真实值')
plt.xlabel('预测值')
plt.show()

# ROC曲线
from sklearn.metrics import roc_curve, auc
y_score = np.random.rand(len(y_true))
fpr, tpr, _ = roc_curve(y_true, y_score)
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.xlabel('假正率')
plt.ylabel('真正率')
plt.title('ROC曲线')
plt.legend()
plt.show()

总结

Matplotlib提供了从基础到高级的完整可视化能力。在ML项目中,善用可视化能帮助你理解数据分布、评估模型性能、发现特征关系。建议结合Seaborn库使用,可以更快速地创建统计图表。