📈 时间序列预测 · 从零到实战

数据可视化基础
Matplotlib · Seaborn
子图布局 · 日期刻度
中小学生色系 · 双边框

🎯 第4章:从折线图到专业可视化 —— 掌握 Matplotlib 绘制时间序列、子图布局、日期刻度格式化,并用 Seaborn 美化。让数据讲故事。

📉 1. 时间序列折线图 Matplotlib 核心

🔹 基本折线图

  • plt.plot(dates, values)
  • 自动识别日期类型
  • 线条样式、颜色、标记

🔸 日期刻度格式化

  • mdates.DateFormatter
  • mdates.WeekdayLocator
  • 旋转标签 fig.autofmt_xdate()
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np

# 生成示例时间序列
dates = pd.date_range('2024-01-01', periods=30, freq='D')
values = np.cumsum(np.random.randn(30)) + 20

fig, ax = plt.subplots(figsize=(10, 3.5))
ax.plot(dates, values, color='#2d6a4f', linewidth=2.5, marker='o', markersize=5)

# 日期格式化
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1))
plt.xticks(rotation=45)
ax.set_title('📅 每日销售趋势 (2024.01)', fontsize=14, fontweight='bold')
plt.tight_layout()
plt.show()
🧩 2. 子图布局 subplots / gridspec
方法说明适用场景
plt.subplots(nrows, ncols)快速创建均匀子图对比多个时间序列
GridSpec自定义子图宽高比仪表板、混合图表
add_subplot()逐个添加子图复杂布局
fig, axes = plt.subplots(2, 2, figsize=(12, 6), sharex=True, sharey=False)
axes[0,0].plot(dates, values, 'seagreen')
axes[0,1].plot(dates, np.sin(values/5), 'tomato')
axes[1,0].plot(dates, values.cumsum(), 'steelblue')
axes[1,1].plot(dates, np.abs(values), 'goldenrod')
plt.suptitle('🌿 多子图时间序列', fontsize=16, y=1.02)
plt.tight_layout()
plt.show()
⏱️ 3. 日期刻度格式化 让时间轴清晰

常用格式化代码

  • %Y 四位年份 · %m 月份 · %d 日
  • %H:%M 小时:分钟
  • %b 英文月份缩写 · %a 星期缩写

定位器 Locator

  • DayLocator
  • WeekdayLocator
  • MonthLocator
  • YearLocator
🎨 4. Seaborn 美化 优雅配色 & 主题
Matplotlib Seaborn ✨ 美化 sns.set_theme(style='whitegrid', palette='muted') sns.lineplot(x='date', y='value', data=df) 🎨 配色: Set2, husl, Paired ... 子图1 (折线) 子图2 (柱状) 子图3 (面积) 子图4 (散点) GridSpec / subplots 灵活布局
import seaborn as sns
import matplotlib.pyplot as plt

sns.set_theme(style='whitegrid', palette='Set2', font='sans-serif')
df = pd.DataFrame({'date': dates, 'value': values})

fig, ax = plt.subplots(figsize=(10, 4))
sns.lineplot(x='date', y='value', data=df, marker='o', linewidth=2.5, ax=ax, color='#2d6a4f')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
plt.xticks(rotation=30)
ax.set_title('🌻 Seaborn 风格时间序列', fontsize=15, fontweight='bold')
plt.tight_layout()
plt.show()
🧪 综合实战 子图 + 日期刻度 + Seaborn

📌 将上述技巧组合:2×1 子图,上为原始序列,下为滚动均值,日期格式化,Seaborn 主题。

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 6), sharex=True)
sns.set_theme(style='ticks', palette='pastel')
sns.lineplot(x=dates, y=values, ax=ax1, color='#2d6a4f', linewidth=2)
ax1.set_title('原始序列', fontsize=13)

rolling = pd.Series(values).rolling(5).mean()
sns.lineplot(x=dates, y=rolling, ax=ax2, color='#d95f02', linewidth=2.5)
ax2.set_title('5日滚动均值', fontsize=13)

ax2.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d'))
ax2.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1))
fig.autofmt_xdate()
plt.suptitle('📊 时间序列分解视图', fontsize=16, y=1.02)
plt.tight_layout()
plt.show()