🎯 第4章:从折线图到专业可视化 —— 掌握 Matplotlib 绘制时间序列、子图布局、日期刻度格式化,并用 Seaborn 美化。让数据讲故事。
plt.plot(dates, values)mdates.DateFormattermdates.WeekdayLocatorfig.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()
| 方法 | 说明 | 适用场景 |
|---|---|---|
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()
%Y 四位年份 · %m 月份 · %d 日%H:%M 小时:分钟%b 英文月份缩写 · %a 星期缩写DayLocatorWeekdayLocatorMonthLocatorYearLocatorimport 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()
📌 将上述技巧组合: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()