对不起,你的PPT数据不够直观,你可能需要让数据动起来

新闻 前端
数据暴增的年代,数据科学家、分析师在被要求对数据有更深的理解与分析的同时,还需要将结果有效地传递给他人。如何让目标听众更直观地理解?当然是将数据可视化啊,而且最好是动态可视化。

 在读技术博客的过程中,我们会发现那些能够把知识、成果讲透的博主很多都会做动态图表。他们的图是怎么做的?难度大吗?这篇文章就介绍了 Python 中一种简单的动态图表制作方法。

对不起,你的PPT数据不够直观,你可能需要让数据动起来

数据暴增的年代,数据科学家、分析师在被要求对数据有更深的理解与分析的同时,还需要将结果有效地传递给他人。如何让目标听众更直观地理解?当然是将数据可视化啊,而且最好是动态可视化。

本文将以线型图、条形图和饼图为例,系统地讲解如何让你的数据图表动起来。

对不起,你的PPT数据不够直观,你可能需要让数据动起来

这些动态图表是用什么做的?

接触过数据可视化的同学应该对 Python 里的 Matplotlib 库并不陌生。它是一个基于 Python 的开源数据绘图包,仅需几行代码就可以帮助开发者生成直方图、功率谱、条形图、散点图等。这个库里有个非常实用的扩展包——FuncAnimation,可以让我们的静态图表动起来。

FuncAnimation 是 Matplotlib 库中 Animation 类的一部分,后续会展示多个示例。如果是首次接触,你可以将这个函数简单地理解为一个 While 循环,不停地在 “画布” 上重新绘制目标数据图。

如何使用 FuncAnimation?

这个过程始于以下两行代码:

  1. import matplotlib.animation as ani 
  2.  
  3. animator = ani.FuncAnimation(fig, chartfunc, interval = 100

从中我们可以看到 FuncAnimation 的几个输入:

  • fig 是用来 「绘制图表」的 figure 对象;
  • chartfunc 是一个以数字为输入的函数,其含义为时间序列上的时间;
  • interval 这个更好理解,是帧之间的间隔延迟,以毫秒为单位,默认值为 200。

这是三个关键输入,当然还有更多可选输入,感兴趣的读者可查看原文档,这里不再赘述。

下一步要做的就是将数据图表参数化,从而转换为一个函数,然后将该函数时间序列中的点作为输入,设置完成后就可以正式开始了。

在开始之前依旧需要确认你是否对基本的数据可视化有所了解。也就是说,我们先要将数据进行可视化处理,再进行动态处理。

按照以下代码进行基本调用。另外,这里将采用大型流行病的传播数据作为案例数据(包括每天的死亡人数)。

  1. import matplotlib.animation as ani 
  2. import matplotlib.pyplot as plt 
  3. import numpy as np 
  4. import pandas as pdurl = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv' 
  5. df = pd.read_csv(url, delimiter=',', header='infer')df_interest = df.loc[ 
  6.     df['Country/Region'].isin(['United Kingdom''US''Italy''Germany']) 
  7.     & df['Province/State'].isna()]df_interest.rename( 
  8.     index=lambda x: df_interest.at[x, 'Country/Region'], inplace=True) 
  9. df1 = df_interest.transpose()df1 = df1.drop(['Province/State''Country/Region''Lat''Long']) 
  10. df1 = df1.loc[(df1 != 0).any(1)] 
  11. df1.index = pd.to_datetime(df1.index) 

绘制三种常见动态图表

绘制动态线型图

如下所示,首先需要做的第一件事是定义图的各项,这些基础项设定之后就会保持不变。它们包括:创建 figure 对象,x 标和 y 标,设置线条颜色和 figure 边距等:

  1. import numpy as np 
  2.  
  3. import matplotlib.pyplot as pltcolor = ['red''green''blue''orange'
  4.  
  5. fig = plt.figure() 
  6.  
  7. plt.xticks(rotation=45, ha="right", rotation_mode="anchor") #rotate the x-axis values 
  8.  
  9. plt.subplots_adjust(bottom = 0.2, top = 0.9) #ensuring the dates (on the x-axis) fit in the screen 
  10.  
  11. plt.ylabel('No of Deaths'
  12.  
  13. plt.xlabel('Dates'

接下来设置 curve 函数,进而使用 .FuncAnimation 让它动起来:

  1. def buildmebarchart(i=int): 
  2.  
  3.     plt.legend(df1.columns) 
  4.  
  5.     p = plt.plot(df1[:i].index, df1[:i].values) #note it only returns the dataset, up to the point i 
  6.  
  7.     for i in range(0,4): 
  8.  
  9.         p[i].set_color(color[i]) #set the colour of each curveimport matplotlib.animation as ani 
  10.  
  11. animator = ani.FuncAnimation(fig, buildmebarchart, interval = 100
  12.  
  13. plt.show() 

动态饼状图

对不起,你的PPT数据不够直观,你可能需要让数据动起来

可以观察到,其代码结构看起来与线型图并无太大差异,但依旧有细小的差别。

  1. import numpy as np 
  2.  
  3. import matplotlib.pyplot as pltfig,ax = plt.subplots() 
  4.  
  5. explode=[0.01,0.01,0.01,0.01] #pop out each slice from the piedef getmepie(i): 
  6.  
  7.     def absolute_value(val): #turn % back to a number 
  8.  
  9.         a  = np.round(val/100.*df1.head(i).max().sum(), 0
  10.  
  11.         return int(a) 
  12.  
  13.     ax.clear() 
  14.  
  15.     plot = df1.head(i).max().plot.pie(y=df1.columns,autopct=absolute_value, label='',explode = explode, shadow = True) 
  16.  
  17.     plot.set_title('Total Number of Deathsn' + str(df1.index[min( i, len(df1.index)-1 )].strftime('%y-%m-%d')), fontsize=12)import matplotlib.animation as ani 
  18.  
  19. animator = ani.FuncAnimation(fig, getmepie, interval = 200
  20.  
  21. plt.show() 

主要区别在于,动态饼状图的代码每次循环都会返回一组数值,但在线型图中返回的是我们所在点之前的整个时间序列。返回时间序列通过 df1.head(i) 来实现,而. max()则保证了我们仅获得最新的数据,因为流行病导致死亡的总数只有两种变化:维持现有数量或持续上升。

  1. df1.head(i).max() 

动态条形图

创建动态条形图的难度与上述两个案例并无太大差别。在这个案例中,作者定义了水平和垂直两种条形图,读者可以根据自己的实际需求来选择图表类型并定义变量栏。

  1. fig = plt.figure() 
  2.  
  3. bar = ''def buildmebarchart(i=int): 
  4.  
  5.     iv = min(i, len(df1.index)-1) #the loop iterates an extra one time, which causes the dataframes to go out of bounds. This was the easiest (most lazy) way to solve this :) 
  6.  
  7.     objects = df1.max().index 
  8.  
  9.     y_pos = np.arange(len(objects)) 
  10.  
  11.     performance = df1.iloc[[iv]].values.tolist()[0
  12.  
  13.     if bar == 'vertical'
  14.  
  15.         plt.bar(y_pos, performance, align='center', color=['red''green''blue''orange']) 
  16.  
  17.         plt.xticks(y_pos, objects) 
  18.  
  19.         plt.ylabel('Deaths'
  20.  
  21.         plt.xlabel('Countries'
  22.  
  23.         plt.title('Deaths per Country n' + str(df1.index[iv].strftime('%y-%m-%d'))) 
  24.  
  25.     else
  26.  
  27.         plt.barh(y_pos, performance, align='center', color=['red''green''blue''orange']) 
  28.  
  29.         plt.yticks(y_pos, objects) 
  30.  
  31.         plt.xlabel('Deaths'
  32.  
  33.         plt.ylabel('Countries')animator = ani.FuncAnimation(fig, buildmebarchart, interval=100)plt.show() 

在制作完成后,存储这些动态图就非常简单了,可直接使用以下代码:

  1. animator.save(r'C:tempmyfirstAnimation.gif'

感兴趣的读者如想获得详细信息可参考:https://matplotlib.org/3.1.1/api/animation_api.html。

 

 

责任编辑:张燕妮 来源: 机器之心
相关推荐

2019-05-21 14:18:09

PygamePython编程语言

2012-09-03 09:21:51

2022-07-13 15:46:57

Python数据可视化代码片段

2015-12-01 13:51:52

Webrtc

2016-11-15 15:10:07

2021-01-18 10:36:13

移动办公首席信息官CIO

2021-08-02 23:19:06

微信小程序人工智能

2019-10-10 09:41:54

AI 数据人工智能

2022-02-24 08:30:24

操作系统CPU程序

2009-06-19 11:18:51

Factory BeaSpring配置

2022-06-07 09:00:32

PythonAI静态图片

2020-11-16 11:50:21

Python代码命令

2013-05-27 15:35:18

用友UAP移动应用移动平台

2012-11-19 14:25:07

数据中心SDN

2012-11-19 16:32:16

数据中心

2010-09-01 17:35:41

云计算

2021-01-08 08:22:25

代码应用程序

2016-12-28 19:46:40

电源数据中心UPS

2019-05-22 15:04:34

Python磁盘IO

2011-06-01 14:51:54

jQuery
点赞
收藏

51CTO技术栈公众号