📉 09 · 数据可视化与图表规范¶
图表是数据分析师的「语言」。本节覆盖选型原则 + 7 类常用图 + 可视化陷阱,全部使用 matplotlib 手绘,强调「先想清楚要表达什么,再选图」。
📋 本节要解决的问题¶
| 想表达什么 | 选什么图 |
|---|---|
| 随时间的变化 | 折线图 |
| 类别之间对比 | 柱状图 / 条形图 |
| 分布长什么样 | 直方图 / 箱线图 |
| 两个变量的关系 | 散点图 |
| 矩阵/交叉表 | 热力图 |
| 转化路径流失 | 漏斗图 |
| 占比结构 | 饼图(少用)/ 堆叠柱 |
Copied!
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'PingFang SC', 'Noto Sans CJK SC', 'Arial Unicode MS']
matplotlib.rcParams['axes.unicode_minus'] = False
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'PingFang SC', 'Noto Sans CJK SC', 'Arial Unicode MS']
matplotlib.rcParams['axes.unicode_minus'] = False
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
1️⃣ 折线图:趋势(DAU 与留存衰减)¶
Copied!
days = np.arange(1, 15)
retention = 0.6 * np.exp(-days/4) + 0.08 # 模拟留存衰减
plt.figure(figsize=(7, 4))
plt.plot(days, retention, marker='o', color='#2563eb')
plt.xlabel('注册后第 N 天')
plt.ylabel('留存率')
plt.title('留存衰减曲线')
plt.grid(alpha=0.3)
plt.show()
days = np.arange(1, 15)
retention = 0.6 * np.exp(-days/4) + 0.08 # 模拟留存衰减
plt.figure(figsize=(7, 4))
plt.plot(days, retention, marker='o', color='#2563eb')
plt.xlabel('注册后第 N 天')
plt.ylabel('留存率')
plt.title('留存衰减曲线')
plt.grid(alpha=0.3)
plt.show()
2️⃣ 柱状图:类别对比(各渠道 GMV)¶
Copied!
channels = ['自然量', '广告', '活动', '合作', '其他']
gmv = [120, 85, 60, 40, 22]
plt.figure(figsize=(7, 4))
bars = plt.bar(channels, gmv, color='#60a5fa')
bars[2].set_color('#f59e0b') # 高亮活动渠道
plt.ylabel('GMV(万元)')
plt.title('各渠道 GMV 贡献')
for i, v in enumerate(gmv):
plt.text(i, v+2, f'{v}', ha='center', fontsize=11)
plt.show()
channels = ['自然量', '广告', '活动', '合作', '其他']
gmv = [120, 85, 60, 40, 22]
plt.figure(figsize=(7, 4))
bars = plt.bar(channels, gmv, color='#60a5fa')
bars[2].set_color('#f59e0b') # 高亮活动渠道
plt.ylabel('GMV(万元)')
plt.title('各渠道 GMV 贡献')
for i, v in enumerate(gmv):
plt.text(i, v+2, f'{v}', ha='center', fontsize=11)
plt.show()
3️⃣ 直方图 + 箱线图:分布¶
Copied!
login_min = np.concatenate([rng.normal(20, 5, 300), rng.normal(55, 10, 60)])
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].hist(login_min, bins=25, color='#34d399', edgecolor='white')
axes[0].set_title('使用时长直方图(双峰)')
axes[0].set_xlabel('分钟')
axes[1].boxplot([rng.normal(50, 15, 100), rng.normal(45, 8, 100)], labels=['A 组', 'B 组'])
axes[1].set_title('A/B 组时长箱线图')
plt.tight_layout()
plt.show()
login_min = np.concatenate([rng.normal(20, 5, 300), rng.normal(55, 10, 60)])
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].hist(login_min, bins=25, color='#34d399', edgecolor='white')
axes[0].set_title('使用时长直方图(双峰)')
axes[0].set_xlabel('分钟')
axes[1].boxplot([rng.normal(50, 15, 100), rng.normal(45, 8, 100)], labels=['A 组', 'B 组'])
axes[1].set_title('A/B 组时长箱线图')
plt.tight_layout()
plt.show()
4️⃣ 散点图:相关关系¶
Copied!
x = rng.uniform(0, 100, 120)
y = 0.8 * x + rng.normal(0, 8, 120)
plt.figure(figsize=(7, 4))
plt.scatter(x, y, alpha=0.6, s=30, color='#8b5cf6')
plt.xlabel('曝光量')
plt.ylabel('点击量')
plt.title('曝光-点击散点(正相关)')
plt.show()
x = rng.uniform(0, 100, 120)
y = 0.8 * x + rng.normal(0, 8, 120)
plt.figure(figsize=(7, 4))
plt.scatter(x, y, alpha=0.6, s=30, color='#8b5cf6')
plt.xlabel('曝光量')
plt.ylabel('点击量')
plt.title('曝光-点击散点(正相关)')
plt.show()
5️⃣ 热力图:留存矩阵 / 交叉表¶
Copied!
# 模拟留同期群存矩阵(注册周 × 第 N 周留存率)
cohorts = pd.DataFrame(rng.uniform(0.2, 0.9, (6, 6)))
for i in range(6):
cohorts.iloc[i, :6-i] = cohorts.iloc[i, :6-i].values
cohorts.iloc[i, 6-i:] = np.nan
plt.figure(figsize=(8, 5))
plt.imshow(cohorts.values, cmap='YlGnBu', aspect='auto', vmin=0, vmax=1)
plt.colorbar(label='留存率')
plt.xticks(range(6), [f'第{i}周' for i in range(6)])
plt.yticks(range(6), [f'注册第{i+1}周' for i in range(6)])
plt.title('同期群留存率热力图(右上为未到期的空值)')
plt.show()
# 模拟留同期群存矩阵(注册周 × 第 N 周留存率)
cohorts = pd.DataFrame(rng.uniform(0.2, 0.9, (6, 6)))
for i in range(6):
cohorts.iloc[i, :6-i] = cohorts.iloc[i, :6-i].values
cohorts.iloc[i, 6-i:] = np.nan
plt.figure(figsize=(8, 5))
plt.imshow(cohorts.values, cmap='YlGnBu', aspect='auto', vmin=0, vmax=1)
plt.colorbar(label='留存率')
plt.xticks(range(6), [f'第{i}周' for i in range(6)])
plt.yticks(range(6), [f'注册第{i+1}周' for i in range(6)])
plt.title('同期群留存率热力图(右上为未到期的空值)')
plt.show()
6️⃣ 漏斗图:转化路径¶
Copied!
stages = ['曝光', '点击', '加购', '支付']
users = [100000, 32000, 9000, 2600]
widths = np.array(users) / users[0]
fig, ax = plt.subplots(figsize=(7, 5))
y = np.arange(len(stages))[::-1]
colors = ['#60a5fa', '#818cf8', '#a78bfa', '#c084fc']
for wi, yi, c, u, s in zip(widths, y, colors, users, stages):
ax.barh(yi, wi, height=0.55, color=c)
ax.text(0.02, yi, f'{s} · {u:,}', va='center', color='white', fontsize=13)
ax.set_yticks(y)
ax.set_yticklabels(stages[::-1])
ax.set_xlim(0, 1)
ax.set_xticks([])
ax.set_title('转化漏斗(相对宽度)')
plt.show()
stages = ['曝光', '点击', '加购', '支付']
users = [100000, 32000, 9000, 2600]
widths = np.array(users) / users[0]
fig, ax = plt.subplots(figsize=(7, 5))
y = np.arange(len(stages))[::-1]
colors = ['#60a5fa', '#818cf8', '#a78bfa', '#c084fc']
for wi, yi, c, u, s in zip(widths, y, colors, users, stages):
ax.barh(yi, wi, height=0.55, color=c)
ax.text(0.02, yi, f'{s} · {u:,}', va='center', color='white', fontsize=13)
ax.set_yticks(y)
ax.set_yticklabels(stages[::-1])
ax.set_xlim(0, 1)
ax.set_xticks([])
ax.set_title('转化漏斗(相对宽度)')
plt.show()
7️⃣ 可视化陷阱(面试必考)¶
Copied!
# 陷阱 1:截断 Y 轴夸大差异
before = rng.normal(100, 2, 50)
after = rng.normal(105, 2, 50)
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].bar(['活动前', '活动后'], [before.mean(), after.mean()], color=['#94a3b8', '#f59e0b'])
axes[0].set_ylim(0, 120)
axes[0].set_title('正常 Y 轴:差异不明显')
axes[1].bar(['活动前', '活动后'], [before.mean(), after.mean()], color=['#94a3b8', '#f59e0b'])
axes[1].set_ylim(98, 107)
axes[1].set_title('截断 Y 轴:差异被夸大')
plt.tight_layout()
plt.show()
print('➡️ 其余陷阱:双 Y 轴误导、3D 饼图、颜色过滥、缺失数据不标注、图片无标题无单位')
# 陷阱 1:截断 Y 轴夸大差异
before = rng.normal(100, 2, 50)
after = rng.normal(105, 2, 50)
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].bar(['活动前', '活动后'], [before.mean(), after.mean()], color=['#94a3b8', '#f59e0b'])
axes[0].set_ylim(0, 120)
axes[0].set_title('正常 Y 轴:差异不明显')
axes[1].bar(['活动前', '活动后'], [before.mean(), after.mean()], color=['#94a3b8', '#f59e0b'])
axes[1].set_ylim(98, 107)
axes[1].set_title('截断 Y 轴:差异被夸大')
plt.tight_layout()
plt.show()
print('➡️ 其余陷阱:双 Y 轴误导、3D 饼图、颜色过滥、缺失数据不标注、图片无标题无单位')
➡️ 其余陷阱:双 Y 轴误导、3D 饼图、颜色过滥、缺失数据不标注、图片无标题无单位
8️⃣ 图表规范清单(交付时自查)¶
- 标题说清「什么 vs 什么」;坐标轴带单位
- 颜色语义一致(红=降/警告,绿=升/好),不超过 5 色
- 图例、注释、数据标签完整;关键结论用文字标出
- 不使用 3D 效果与装饰性网格
- 单图一个观点;多观点拆子图
- 中文字体统一(如本 notebook 的字体配置)
📝 自测清单¶
- 能根据「想表达什么」选对图表类型
- 能画出折线/柱状/直方/箱线/散点/热力/漏斗七种图
- 能列举 5 个以上可视化陷阱并解释危害
- 能说出交付级图表的规范要点