实现功能:
python绘制带误差阴影的时间序列图。
实现代码:
1 | from scipy.stats import sem |
2 | import pandas as pd |
3 | import matplotlib.pyplot as plt |
4 | # Import Data |
5 | df_raw = pd.read_csv('F:\数据杂坛\datasets\orders_45d.csv', |
6 | parse_dates=['purchase_time', 'purchase_date']) |
7 | |
8 | # Prepare Data: Daily Mean and SE Bands |
9 | df_mean = df_raw.groupby('purchase_date').quantity.mean() |
10 | df_se = df_raw.groupby('purchase_date').quantity.apply(sem).mul(1.96) |
11 | |
12 | # Plot |
13 | plt.figure(figsize=(10, 6), dpi=80) |
14 | plt.ylabel("Daily Orders", fontsize=12) |
15 | x = [d.date().strftime('%Y-%m-%d') for d in df_mean.index] |
16 | plt.plot(x, df_mean, color="#c72e29", lw=2) |
17 | plt.fill_between(x, df_mean - df_se, df_mean + df_se, color="#f8f2e4") |
18 | |
19 | # Decorations |
20 | # Lighten borders |
21 | plt.gca().spines["top"].set_alpha(0) |
22 | plt.gca().spines["bottom"].set_alpha(1) |
23 | plt.gca().spines["right"].set_alpha(0) |
24 | plt.gca().spines["left"].set_alpha(1) |
25 | plt.xticks(x[::6], [str(d) for d in x[::6]], fontsize=12) |
26 | plt.title("Daily Order Quantity of Brazilian Retail with Error Bands (95% confidence)",fontsize=14) |
27 | |
28 | # Axis limits |
29 | s, e = plt.gca().get_xlim() |
30 | plt.xlim(s, e - 2) |
31 | plt.ylim(4, 10) |
32 | |
33 | # Draw Horizontal Tick lines |
34 | for y in range(5, 10, 1): |
35 | plt.hlines(y, |
36 | xmin=s, |
37 | xmax=e, |
38 | colors='black', |
39 | alpha=0.5, |
40 | linestyles="--", |
41 | lw=0.5) |
42 | |
43 | plt.show() |
实现效果:
喜欢记得点赞,在看,收藏,
关注V订阅号:数据杂坛,获取数据集,完整代码和效果,将持续更新!
| 留言与评论(共有 0 条评论) “” |