数据可视化:Matplotlib与Seaborn

Python 数据分析与人工智能 · 第3篇

◀ 第2篇 Pandas 3 / 5 第4篇 机器学习 ▶

数据分析师的终极目标不是算出一个数字,而是用数据讲一个好故事。可视化正是"让数据开口说话"的桥梁。本篇将系统讲解 Matplotlib 的基础绘图和 Seaborn 的高级统计图表,并通过 Titanic 数据集完成一份完整的可视化分析报告。

📖 本篇目录

1 为什么需要可视化?
2 Matplotlib 基础:figure/axes 与折线图
3 柱状图与散点图
4 直方图与箱线图
5 Seaborn:一行代码画精美统计图
6 子图布局与图表美化
7 实战:Titanic 可视化分析报告

一、为什么需要可视化?

先看一个经典案例——安斯科姆四重奏(Anscombe's Quartet):四组数据的均值、方差、相关系数几乎完全相同,但画出来却截然不同。

安斯科姆四重奏 — 统计量完全相同,图形完全不同

统计量 数据集I 数据集II 数据集III 数据集IV
x均值 9.0 9.0 9.0 9.0
y均值 7.50 7.50 7.50 7.50
相关系数 0.816 0.816 0.816 0.816

结论:光看数字不够,必须画图!

Python 中最常用的两大可视化库:

特性 Matplotlib Seaborn
定位 底层绘图引擎 高级统计图表
代码量 较多,细粒度控制 一行代码出图
美观度 默认样式朴素 默认就很精美
Pandas集成 需手动传数据 直接传DataFrame
关系 Seaborn 基于 Matplotlib 构建,两者配合使用

二、Matplotlib 基础与折线图

Matplotlib 的核心概念是 Figure(画布) 和 Axes(坐标系)。Figure 是整张图,Axes 是里面的子图(包含坐标轴、数据等)。

Figure(画布)

Axes 1
Axes 2

一个 Figure 可以包含多个 Axes(子图)

Python Matplotlib 折线图
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import matplotlib.pyplot as plt
import numpy as np
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 生成数据
months = ["1月","2月","3月","4月","5月","6月"]
sales_a = [120, 135, 148, 160, 155, 178]
sales_b = [90, 110, 105, 130, 142, 160]
# 创建画布
fig, ax = plt.subplots(figsize=(10, 6))
# 绘制两条折线
ax.plot(months, sales_a, 'o-', color='#7c3aed',
linewidth=2, label="产品A")
ax.plot(months, sales_b, 's--', color='#e53e3e',
linewidth=2, label="产品B")
# 添加标注
ax.set_title("上半年销售趋势对比", fontsize=16)
ax.set_xlabel("月份")
ax.set_ylabel("销售额(万元)")
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("sales_trend.png", dpi=150)
plt.show()

💡 小贴士:中文显示问题

Matplotlib 默认不支持中文,需设置 plt.rcParams['font.sans-serif'] = ['SimHei'](Windows)或 ['Arial Unicode MS'](Mac)。每次绘图前设置一次即可。

三、柱状图与散点图

柱状图:分类对比

柱状图最适合比较不同类别之间的数值差异:

Python 柱状图绘制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import matplotlib.pyplot as plt
categories = ["电子产品", "服装", "食品", "图书"]
q1_sales = [450, 320, 280, 150]
q2_sales = [520, 380, 310, 180]
fig, ax = plt.subplots(figsize=(10, 6))
x = np.arange(len(categories))
width = 0.35
# 分组柱状图
bars1 = ax.bar(x - width/2, q1_sales, width,
label="Q1", color="#7c3aed")
bars2 = ax.bar(x + width/2, q2_sales, width,
label="Q2", color="#a78bfa")
# 在柱顶添加数值标签
for bar in bars1 + bars2:
h = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2, h + 5,
f"{h}", ha="center", fontsize=10)
ax.set_xticks(x)
ax.set_xticklabels(categories)
ax.set_title("各品类季度销售对比")
ax.legend()
plt.show()

散点图:相关性探索

散点图用于观察两个变量之间的关系模式——正相关、负相关还是无关:

Python 散点图绘制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import matplotlib.pyplot as plt
import numpy as np
# 模拟数据:学习时长 vs 考试成绩
np.random.seed(42)
hours = np.random.uniform(1, 10, 50)
scores = 40 + hours * 5.5 + np.random.normal(0, 8, 50)
fig, ax = plt.subplots(figsize=(8, 6))
# 散点图(颜色映射按分数)
scatter = ax.scatter(
hours, scores,
c=scores, # 按分数着色
cmap="viridis", # 配色方案
s=80, # 点大小
alpha=0.7, # 透明度
edgecolors="white"
)
# 添加趋势线
z = np.polyfit(hours, scores, 1)
p = np.poly1d(z)
ax.plot(hours, p(hours), "r--", alpha=0.8,
label="趋势线")
ax.set_xlabel("每日学习时长(小时)")
ax.set_ylabel("考试成绩")
ax.set_title("学习时长与成绩的关系")
plt.colorbar(scatter, label="成绩")
ax.legend()
plt.show()

四、直方图与箱线图

了解数据分布是数据分析的重要一步。直方图和箱线图是两种最常用的分布可视化工具:

图表类型 适用场景 展示信息
直方图 连续变量分布 频率、分布形态
箱线图 多组分布对比 中位数、四分位、异常值
Python 直方图与箱线图
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
scores = np.random.normal(loc=75, scale=12, size=200)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
# 左:直方图
ax1.hist(scores, bins=20, color="#7c3aed",
alpha=0.7, edgecolor="white")
ax1.axvline(scores.mean(), color="red",
linestyle="--", label="均值")
ax1.set_title("成绩分布直方图")
ax1.set_xlabel("分数")
ax1.set_ylabel("人数")
ax1.legend()
# 右:箱线图(多组对比)
data = [
np.random.normal(75, 12, 100), # A班
np.random.normal(80, 8, 100), # B班
np.random.normal(70, 15, 100), # C班
]
bp = ax2.boxplot(data, labels=["A班","B班","C班"],
patch_artist=True)
colors = ["#7c3aed", "#a78bfa", "#c4b5fd"]
for patch, color in zip(bp["boxes"], colors):
patch.set_facecolor(color)
ax2.set_title("三班成绩箱线图对比")
ax2.set_ylabel("分数")
plt.tight_layout()
plt.show()

💡 小贴士:箱线图怎么看?

箱体中线 = 中位数;箱体上下 = 25%/75%分位数;须线 = 1.5倍IQR范围;须线外的圆点 = 异常值。箱线图一张图就能看清数据分布和离群点。

五、Seaborn:一行代码画精美统计图

Seaborn 建立在 Matplotlib 之上,提供更简洁的 API 和更精美的默认样式。它直接接受 DataFrame 作为输入,并自动处理分组和统计。

Python Seaborn 常用图表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
# 加载内置数据集
tips = sns.load_dataset("tips")
# 设置Seaborn样式
sns.set_theme(style="whitegrid")
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 1. 小提琴图:分布 + 密度
sns.violinplot(data=tips, x="day", y="total_bill",
ax=axes[0,0], palette="purples")
axes[0,0].set_title("每日账单分布")
# 2. 带回归线的散点图
sns.regplot(data=tips, x="total_bill", y="tip",
ax=axes[0,1], color="#7c3aed")
axes[0,1].set_title("账单与小费关系")
# 3. 分类柱状图(自动计算均值和置信区间)
sns.barplot(data=tips, x="day", y="total_bill",
hue="sex", ax=axes[1,0],
palette="Set2")
axes[1,0].set_title("性别×星期 平均账单")
# 4. 热力图(相关性矩阵)
numeric = tips.select_dtypes(include="number")
corr = numeric.corr()
sns.heatmap(corr, annot=True, cmap="RdPu",
ax=axes[1,1], fmt=".2f")
axes[1,1].set_title("特征相关性热力图")
plt.tight_layout()
plt.show()

六、子图布局与图表美化

实际报告中,经常需要把多个图表排列在一起。Matplotlib 提供了灵活的子图布局方案:

⚠️ 常见错误:忘记 plt.show() 或图表重叠

每次绘图后记得调用 plt.show(),否则 Jupyter 中可能不显示。多次绘图间用 plt.figure() 创建新画布,避免图表叠加在一起。

Python 图表美化实用技巧
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import matplotlib.pyplot as plt
import numpy as np
# 全局样式设置
plt.rcParams.update({
"figure.facecolor": "white",
"axes.facecolor": "#fafafa",
"axes.edgecolor": "#cccccc",
"font.size": 12,
})
x = np.linspace(0, 10, 100)
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
fig.suptitle("美化图表示例", fontsize=16,
fontweight="bold", y=0.98)
# 渐变色填充
axes[0,0].fill_between(x, np.sin(x),
alpha=0.3, color="#7c3aed")
axes[0,0].plot(x, np.sin(x), color="#7c3aed",
linewidth=2)
# 添加注释箭头
axes[0,1].plot(x, np.cos(x), color="#e53e3e")
axes[0,1].annotate("峰值", xy=(0,1),
xytext=(2,0.8),
arrowprops=dict(arrowstyle="->"))
plt.tight_layout()
plt.savefig("polished_charts.png",
dpi=150, bbox_inches="tight")
plt.show()

七、实战:Titanic 可视化分析报告

泰坦尼克号数据集是数据分析的经典入门数据集。下面我们用完整流程完成从加载到可视化的分析报告:

Python Titanic 可视化分析
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# 加载数据(Seaborn内置)
df = sns.load_dataset("titanic")
sns.set_theme(style="whitegrid")
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
fig.suptitle("Titanic 乘客生存分析",
fontsize=16, fontweight="bold")
# 图1:各舱位生存人数(堆叠柱状图)
surv = df.groupby(["class","survived"]).size()
surv.unstack().plot(kind="bar",
ax=axes[0,0], color=["#e53e3e","#7c3aed"])
axes[0,0].set_title("各舱位死亡/存活人数")
axes[0,0].set_ylabel("人数")
# 图2:年龄分布(按生存状态)
sns.histplot(data=df, x="age", hue="survived",
kde=True, ax=axes[0,1],
palette=["#e53e3e", "#7c3aed"])
axes[0,1].set_title("存活/死亡乘客年龄分布")
# 图3:性别与生存率
surv_rate = df.groupby("sex")["survived"].mean()
surv_rate.plot(kind="bar", ax=axes[1,0],
color=["#7c3aed", "#a78bfa"])
axes[1,0].set_title("性别生存率对比")
axes[1,0].set_ylabel("生存率")
axes[1,0].set_ylim(0, 1)
# 图4:票价箱线图(按舱位)
sns.boxplot(data=df, x="class", y="fare",
ax=axes[1,1], palette="purples")
axes[1,1].set_title("各舱位票价分布")
plt.tight_layout()
plt.savefig("titanic_analysis.png", dpi=150)
plt.show()
# 打印关键数据发现
print("=== 关键发现 ===")
print(f"女性生存率: {surv_rate['female']:.1%}")
print(f"男性生存率: {surv_rate['male']:.1%}")

通过这4张图,我们清楚地看到了几个关键发现:

📝 本篇小结

核心知识点回顾:

✅ Matplotlib 核心概念:Figure(画布)+ Axes(坐标系)

✅ 折线图看趋势,柱状图看对比,散点图看关系

✅ 直方图看分布,箱线图看分布+异常值

✅ Seaborn 一行代码画出精美统计图

✅ 好图表要讲故事,不是堆数据

👉 下一篇预告

机器学习入门:Scikit-learn 实战

掌握了数据处理和可视化之后,下一步是让机器从数据中"学习规律"。下一篇我们将进入机器学习的世界,学习 Scikit-learn 的统一接口,完成分类、回归和模型评估的完整流程。

第4篇 · 机器学习入门

Python 数据分析与人工智能 · 系列学习文章

坚持原创,每一行代码均可运行

相关阅读
想动手实操?你需要一台服务器
学编程离不开动手实操。一台入门级云服务器是你最好的练习场,数据库、对象存储、CDN、短信也都能用上,入门配置很便宜,够你把学到的东西真跑一遍。
查看腾讯云优惠查看阿里云优惠
想系统入门?配一本书
看文章学的是零散知识点,想系统入门还得有一本书打底。
Python 入门书C 与 Python 入门Web 开发书