趋势(四)利用python绘制流图

趋势(四)利用python绘制流图

流图(Streamgraph)简介

1

流图是一种围绕中心轴偏移的堆叠面积图,从而形成流动的有机形状。数据在不同的阶段产生了结构性的变化时,通过可视化手段看数据成分的变动大小及变动方向。

绘制流图

import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

# 自定义数据
x = np.arange(1990, 2020)
y = [np.random.randint(0, 5, size=30) for _ in range(5)]

绘制基本的堆叠面积图

fig, ax = plt.subplots(figsize=(10, 7))

ax.stackplot(x, y);

2

修改baseline

fig, ax = plt.subplots(figsize=(10, 7))

ax.stackplot(x, y, baseline="sym")
ax.axhline(0, color="black", ls="--");

3

平滑曲线

# 自定义高斯平滑
def gaussian_smooth(x, y, sd):
    weights = np.array([stats.norm.pdf(x, m, sd) for m in x])
    weights = weights / weights.sum(1)
    return (weights * y).sum(1)

fig, ax = plt.subplots(figsize=(10, 7))

y_smoothed = [gaussian_smooth(x, y_, 1) for y_ in y] # 权重为1,权重越大越平滑,但是波动越小
ax.stackplot(x, y_smoothed, baseline="sym");

4

调整平滑程度

# 增加网格使其更平滑
def gaussian_smooth(x, y, grid, sd):
    weights = np.transpose([stats.norm.pdf(grid, m, sd) for m in x])
    weights = weights / weights.sum(0)
    return (weights * y).sum(1)

fig, ax = plt.subplots(figsize=(10, 7))

grid = np.linspace(1985, 2025, num=500)
y_smoothed = [gaussian_smooth(x, y_, grid, 1) for y_ in y] # 权重为1,权重越大越平滑,但是波动越小
ax.stackplot(grid, y_smoothed, baseline="sym");

5

美化颜色

COLORS = ["#D0D1E6", "#A6BDDB", "#74A9CF", "#2B8CBE", "#045A8D"]
fig, ax = plt.subplots(figsize=(10, 7))

ax.stackplot(grid, y_smoothed, colors=COLORS, baseline="sym");

6

总结

以上基于matplotlib绘制堆叠面积图的基础上,调整baseline和平滑曲线完成了流图的绘制。

共勉~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值