时间序列动态图是显示时间演变的非常强大的工具,但 matplotlib 的默认动态图很简单,不太适合用于比较多个时间序列。

动态图被广泛使用:从解释神经网络如何训练,到显示合成时间序列统计数据或波动率异常时应该选择何种基金等问题。

假设我们想知道在新冠病毒流行期间哪个股票市场的发展最好,怎样使人们都可以直观的判断出来呢?我建议创建动态图,因为它更简明、更清晰。我们从 2D 开始,到 3D,最后用 3D 网格来表示。

由于这篇文章的目的是改进时间序列动画,我们将使用 GDP(国内生产总值)最高的 10 个欧洲国家的股票指数演变作为数据。

2019年GDP最高的欧洲国家(不包括俄罗斯和土耳其)是:

# Country Country code Stock Index
1 Germany GER DAX
2 United Kingdom UK UKX
3 France FR CAC
4 Italy IT FTSEMIB
5 Spain ES IBEX
6 Netherlands NL AEX
7 Switzerland CH SMI
8 Poland* PL WIG
9 Sweden SE OMX
10 Belgium BE BEL20

为了比较 2020 年欧洲股票指数的涨跌,所有动态图都显示了指数从 01/01/2019 到 29/01/2021 1 年(261 天)的的滚动股价 。

2D动态图

第一种方法是创建所有滚动股价的2D线图:

def update_lines_2D(num, data, columns, dates, cmap, lines, ax):'''Function that updates the lines of a plot in 2D'''# get the slicecurrent_slice = data[num:261+num, :]current_dates = dates[num:261+num]# for each index...for i in range(current_slice.shape[1]):# get the coordinatesx = np.array(np.arange(current_slice.shape[0]))y = np.array(current_slice[:, i])# crete points and segments to colorpoints = np.array([x, y]).T.reshape(-1, 1, 2)segments = np.concatenate([points[:-1], points[1:]], axis=1)# Create a continuous norm to map from data points to colorsnorm = plt.Normalize(-0.22, 0.22)        lines[i].set_segments(segments)lines[i].set_array(y)lines[i].set_color(cmap(y[-1] * 2.5 + 0.5))# update the ticks and labelsax.set_xticklabels([dates[int(val)+num].strftime('%m/%y') for val in ax.get_xticks()[:-1]] + [''])ax.legend(loc='center right', bbox_to_anchor=(1.32, 0.5), fancybox=True, facecolor=(.95,.95,.95,1), framealpha=1, shadow=False, frameon=True, ncol=1, columnspacing=0, prop={'family': 'DejaVu Sans Mono'})# return the linesreturn linesdef init_lines_2D():'''Function that initiates the lines of a plot in 2D'''for line in lines:line.set_array([])return lines

动画看起来很酷,但是当线条在时间上重叠时很难比较索引,因为它们具有相同的颜色图。

这可以通过为每个索引选择不同的颜色来解决,但会降低绘图的可读性。

3D动态图

在第二种方法中,添加了第三维。它在给定的 z 坐标中分隔每个索引,创建以下动画:

def update_lines_3D(num, data, columns, dates, cmap, lines, ax):'''Function that updates the lines of a plot in 2D'''# get the slicecurrent_slice = data[num:261+num, :]current_dates = dates[num:261+num]# for each index...for i in range(current_slice.shape[1]):# get the coordinatesx = np.arange(current_slice.shape[0])y = np.tile(i, current_slice.shape[0])z = np.array(current_slice[:, i])# crete points and segments to colorpoints = np.array([x, y, z]).T.reshape(-1, 1, 3)segments = np.concatenate([points[:-1], points[1:]], axis=1)# Create a continuous norm to map from data points to colorsnorm = plt.Normalize(-0.19, 0.19)        lines[i].set_segments(segments)lines[i].set_array(z)lines[i].set_color(cmap(z[-1] * 2.5 + 0.5))# update the ticks and labelsax.set_xticklabels([dates[int(val)+num].strftime('%m/%y') for val in ax.get_xticks()[:-1]] + [''], rotation=0, fontdict={'verticalalignment': 'top', 'horizontalalignment': 'center'})ax.legend(loc='center right', bbox_to_anchor=(1.1, 0.46), fancybox=True, facecolor=(.95,.95,.95,1), framealpha=1, shadow=False, frameon=True, ncol=1, columnspacing=0, prop={'family': 'DejaVu Sans Mono'})# return the linesreturn linesdef init_lines_3D():for line in lines:line.set_array([])return lines

这个动画看起来比2D版本更酷,但它有一个很大的缺点:深度感完全丧失,不同项目进行比较非常困难。不过我们可以添加一个网格。

3D网格动态图

最后,添加一条连接每个时间步长的所有值的线,创建网格:

def update_mesh_lines_3D(num, data, columns, dates, cmap, lines, mesh_lines, ax):'''Function that updates the lines of a plot in 2D'''# get the slice
#     current_slice = data[num:261+num, :]current_slice = data[num:int(261/2)+num, :]# for each index...for i in range(current_slice.shape[1]):# get the coordinatesx = np.arange(current_slice.shape[0])y = np.tile(i, current_slice.shape[0])z = np.array(current_slice[:, i])# crete points and segments to colorpoints = np.array([x, y, z]).T.reshape(-1, 1, 3)segments = np.concatenate([points[:-1], points[1:]], axis=1)# Create a continuous norm to map from data points to colorsnorm = plt.Normalize(-0.19, 0.19)        lines[i].set_segments(segments)lines[i].set_array(z)lines[i].set_color(cmap(z[-1] * 2.5 + 0.5))# counter to check the current mesh linecounter = 0# for each day...for j in range(current_slice.shape[0]):if j % 1 == 0:# get the coordinatesx = np.tile(j, current_slice.shape[1])y = np.arange(current_slice.shape[1])z = np.array(current_slice[j, :])# crete points and segments to colorpoints = np.array([x, y, z]).T.reshape(-1, 1, 3)segments = np.concatenate([points[:-1], points[1:]], axis=1)# Set the values used for colormappingnorm = plt.Normalize(-0.22, 0.22)        mesh_lines[counter].set_segments(segments)mesh_lines[counter].set_array(z)counter += 1# update the ticks and labelsax.set_xticklabels([dates[int(val)+num].strftime('%m/%y') for val in ax.get_xticks()[:-1]] + [''], rotation=0, fontdict={'verticalalignment': 'top', 'horizontalalignment': 'center'})ax.legend(loc='center right', bbox_to_anchor=(1.1, 0.46), fancybox=True, facecolor=(.95,.95,.95,1), framealpha=1, shadow=False, frameon=True, ncol=1, columnspacing=0, prop={'family': 'DejaVu Sans Mono'})# return the linesreturn linesdef init_mesh_lines_3D():for line in lines:line.set_array([])return lines

看看这个动画,网格确实有助于以更清晰的方式比较指数随时间的变化情况,从而得出更好的结论。

结论

从3D网格图中,可以得出以下结论:

UKX(英国)和IBEX(ES)是下跌前和复苏期间最弱的指数。DAX (GER)、OMX (SE)、SMI (CH) 和 AEX (NL) 是下跌前和复苏期间最强的指数。CAC (FR)、FTSEMIB (IT) 和 BEL20 (BE) 在秋季之前是最强的,它们有很小的恢复。看看 2D 动态图,人们可能会得出相同的结论,但会变得更难。

扫描本文最下方二维码获取全部完整源码和Jupyter Notebook 文件打包下载。

长按扫码获取完整源码

用 matplotlib 绘制 3D 时间序列动态图相关推荐

  1. python matplotlib绘制 3D图像专题 (三维柱状图、曲面图、散点图、曲线图合集)

    python matplotlib 绘制3D图表 文章目录 1. 绘制3D柱状图 2. 绘制3D曲面图 ① 示例1 ② 示例2 3.绘制3D散点图 4. 绘制3D曲线图       ʚʕ̯•͡˔•̯᷅ ...

  2. 使用matplotlib绘制3D立方体图

    这个repo 用来记录一些python技巧.书籍.学习链接等,欢迎star github地址 使用matplotlib绘制3D立方体图(含两种样式) # -*- coding: utf-8 -*- # ...

  3. python绘制三维曲面图-Python中使用Matplotlib绘制3D图形示例

    原标题:Python中使用Matplotlib绘制3D图形示例 3D图形能给我们对数据带来更加深入地理解.python的matplotlib库就包含了丰富的3D绘图工具.3D图形在数据分析.数据建模. ...

  4. 使用Matplotlib绘制3D图形

    本文是Matplotlib的第二篇文章,会讲解如何通过Matplotlib绘制3D图形.关于Matplotlib的第一篇文章,请看这里:Python绘图库Matplotlib入门教程. 测试环境 由于 ...

  5. python代码示例图形-Python使用matplotlib绘制3D图形(代码示例)

    本篇文章给大家带来的内容是关于Python使用matplotlib绘制3D图形(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 3D图形在数据分析.数据建模.图形和图像处理 ...

  6. matplotlib绘制3D图像

    用Axes3D类创建3d ax import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3Dfig = plt.fig ...

  7. python制作3d相册代码_Python使用matplotlib绘制3D图形(代码示例)

    本篇文章给大家带来的内容是关于Python使用matplotlib绘制3D图形(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 3D图形在数据分析.数据建模.图形和图像处理 ...

  8. 使用Matplotlib绘制3D动画

    使用Matplotlib绘制3D动图 主角是FuncAnimation函数,通过不断地调用func函数来实现动画,还可以使用save(filename, writer=None, fps=None, ...

  9. Matplotlib 绘制 3D 曲面动画

    Matplotlib 绘制 3D 曲面动画 本文介绍如何使用 Python 中的 Matplotlib 库来绘制动态的 3D 曲面.示例如下: 环境 macOS 11.6 python 3.8 数据 ...

最新文章

  1. trap信号捕捉命令介绍与shell结合实战讲解
  2. ASP.NET系统 + Access数据库
  3. 前端基础12:递归调用,快速排序和简单DOM元素操作
  4. matlab——sparse函数和full函数
  5. c# 多线程 调用带参数函数
  6. Sitecore A / B测试
  7. 5个Vue.js项目的令人敬畏的模板
  8. CnCiswumWN
  9. UNIX-LINUX编程实践教程-第五章-实例代码注解-echostate.c
  10. 机器人周志_机器人教学的意义
  11. PHP第一季视频教程.李炎恢.学习笔记(三)(第2章 基本语法(2))
  12. 构筑城市生命线:应急管理需要新思路,全域能力成关键
  13. VBA之FormulaR1C1属性
  14. java modify的使用方法图解,经过JDT修改(Modify)Java代码的流程步骤
  15. rosbag命令 | EVO工具 的使用
  16. ionic4-ts 字符串中获取汉字与去掉汉字
  17. 知乎没有告诉你:年入百万有多难。
  18. AndroidVideoCache源码赏析
  19. 介绍matlab的概要和功能介绍
  20. 前端学习2——CSS3

热门文章

  1. java.io.IOException: FIS_AUTH_ERROR in Android Firebase
  2. 【Rochester】MongoDB的基本语法和使用
  3. 通达信手机版分时图指标大全_通达信精选指标——主力潜伏中优化版
  4. python 离群值_如何从Numpy数组中删除离群值
  5. [http-nio-8080-exec-9] com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getPoolManager
  6. 大数据分析界的“神兽”Apache Kylin初解
  7. [Linux]基本体系结构
  8. Adobe acrobat修改批注名字
  9. 魔百盒CM211-2 ZG(朝哥代工)无WIFI版线刷救砖包(当贝桌面)
  10. DIY BMP类 (接续)