Matplotlib 与 Seaborn 数据可视化进阶
数据可视化是数据分析的"最后一公里",好的图表能让洞察一目了然。Matplotlib 的灵活性加上 Seaborn 的统计图表,足以应对绝大多数可视化需求。
自定义主题让你的图表风格统一:
import matplotlib.pyplot as plt
import seaborn as sns
# 自定义主题
plt.rcParams.update({
"figure.facecolor": "#fafafa",
"axes.facecolor": "#fafafa",
"axes.grid": True,
"grid.alpha": 0.3,
"font.family": "sans-serif",
"font.size": 12,
})
# Seaborn 配色
sns.set_palette("husl")
多子图布局是复杂报告的常见需求:
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 分布对比
sns.histplot(data=df, x="price", hue="category", ax=axes[0, 0])
# 箱线图
sns.boxplot(data=df, x="category", y="price", ax=axes[0, 1])
# 散点矩阵
sns.scatterplot(data=df, x="feature1", y="feature2",
size="price", hue="category", ax=axes[1, 0])
# 热力图
corr = df.select_dtypes(include="number").corr()
sns.heatmap(corr, annot=True, fmt=".2f", cmap="RdBu_r", ax=axes[1, 1])
plt.tight_layout()
plt.savefig("report.png", dpi=150, bbox_inches="tight")
对于交互式可视化,Plotly 和 Altair 是更好的选择。但在生成报告和论文图表时,Matplotlib 的像素级控制能力无可替代。建议将常用的图表模板封装为函数,配合 Jupyter Magic 命令,实现一键生成标准化报告。