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

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

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

如何使用 FuncAnimation?

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

importmatplotlib.animation asani

animator = ani.FuncAnimation(fig, chartfunc, interval = 100)

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

fig 是用来 「绘制图表」的 figure 对象;

chartfunc 是一个以数字为输入的函数,其含义为时间序列上的时间;

interval 这个更好理解,是帧之间的间隔延迟,以毫秒为单位,默认值为 200。

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

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

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

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

importmatplotlib.animation asani

importmatplotlib.pyplot asplt

importnumpy asnp

importpandas aspdurl = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv'

df = pd.read_csv(url, delimiter= ',', header= 'infer')df_interest = df.loc[

df[ 'Country/Region'].isin([ 'United Kingdom', 'US', 'Italy', 'Germany'])

& df[ 'Province/State'].isna]df_interest.rename(

index= lambdax: df_interest.at[x, 'Country/Region'], inplace= True)

df1 = df_interest.transposedf1 = df1.drop([ 'Province/State', 'Country/Region', 'Lat', 'Long'])

df1 = df1.loc[(df1 != 0).any( 1)]

df1.index = pd.to_datetime(df1.index)

绘制三种常见动态图表

绘制动态线型图

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

importnumpy asnp

importmatplotlib.pyplot aspltcolor = [ 'red', 'green', 'blue', 'orange']

fig = plt.figure

plt.xticks(rotation= 45, ha= "right", rotation_mode= "anchor") #rotate the x-axis values

plt.subplots_adjust(bottom = 0.2, top = 0.9) #ensuring the dates (on the x-axis) fit in the screen

plt.ylabel( 'No of Deaths')

plt.xlabel( 'Dates')

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

defbuildmebarchart(i=int):

plt.legend(df1.columns)

p = plt.plot(df1[ :i].index, df1[ :i].values) #note it only returns the dataset, up to the point i

fori inrange( 0, 4):

p[i].set_color(color[i]) #set the colour of each curveimport matplotlib.animation as ani

animator = ani.FuncAnimation(fig, buildmebarchart, interval = 100)

plt.show

动态饼状图

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

importnumpy asnp

importmatplotlib.pyplot aspltfig,ax = plt.subplots

explode=[ 0.01, 0.01, 0.01, 0.01] #pop out each slice from the piedef getmepie(i):

defabsolute_value(val):#turn % back to a number

a = np.round(val/ 100.*df1.head(i).max.sum, 0)

returnint(a)

ax.clear

plot = df1.head(i).max.plot.pie(y=df1.columns,autopct=absolute_value, label= '',explode = explode, shadow = True)

plot.set_title( 'Total Number of Deathsn'+ str(df1.index[min( i, len(df1.index) -1)].strftime( '%y-%m-%d')), fontsize= 12) importmatplotlib.animation asani

animator = ani.FuncAnimation(fig, getmepie, interval = 200)

plt.show

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

df1.head( i) .max

动态条形图

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

fig = plt.figure

bar = ''def buildmebarchart(i=int):

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 :)

objects = df1. max.index

y_pos = np.arange( len(objects))

performance = df1.iloc [[iv]].values.tolist[ 0]

ifbar == 'vertical':

plt.bar(y_pos, performance, align= 'center', color=[ 'red', 'green', 'blue', 'orange'])

plt.xticks(y_pos, objects)

plt.ylabel( 'Deaths')

plt.xlabel( 'Countries')

plt.title( 'Deaths per Country n'+ str(df1.index[iv].strftime( '%y-%m-%d')))

else:

plt.barh(y_pos, performance, align= 'center', color=[ 'red', 'green', 'blue', 'orange'])

plt.yticks(y_pos, objects)

plt.xlabel( 'Deaths')

plt.ylabel( 'Countries')animator = ani.FuncAnimation(fig, buildmebarchart, interval= 100)plt.show

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

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

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

原文链接:https://towardsdatascience.com/learn-how-to-create-animated-graphs-in-python-fce780421afe

python制作ppt动画_卧槽,还能这么玩!用Python生成动态PPT相关推荐

  1. python制作简单动画_把数据摇起来!用Python制作动画可视化效果!

    Python 中有很多不错的数据可视化库,但是极少能渲染 GIF 图或视频动画效果.本文就分享一下如何用 MoviePy 作为其他可视化库的通用插件,制作动画可视化效果,毕竟这年头,没图不行,有动图更 ...

  2. python制作简单动画_让数据动起来!用python制作动画可视化效果,让数据不再枯燥!...

    MoviePy允许我们自定义的动画功能make_frame (t).函数将返回视频帧时间t(以秒为单位):根据Mayavi Mayavi做出动画是一个Python模块,可以使交互式3 d数据可视化.在 ...

  3. 用python制作3d动画_-用 Python 做科学计算--Visual-制作3D演示动画

    # Visual-制作3D演示动画 [Visual](http://vpython.org) 是Python的一个简单易用的3D图形库,使用它可以快速创建3D场景.动画.和TVTK相比它更加适合于创建 ...

  4. 如何用python制作三维动画_用Python制作3D动画

    很多小伙伴可能不知道,在3D动画甚至电影制作的过程中,Python也在其中扮演了很重要的角色呢! 比如皮克斯的动画片一般使用Maya软件制作,并且流程中使用到了大量的Maya Python插件. 另外 ...

  5. python开发ps插件_你还在用PS?Python 20行代码批量抠图

    抠图前 vs Python自动抠图后 在日常的工作和生活中,我们经常会遇到需要抠图的场景,即便是只有一张图片需要抠,也会抠得我们不耐烦,倘若遇到许多张图片需要抠,这时候你的表情应该会很有趣. Pyth ...

  6. 如何用python制作三维动画_课件中三维动画的Python实现

    课件中三维动画的 Python 实现 李保源 [期刊名称] <福建电脑> [年 ( 卷 ), 期] 2007(000)007 [摘要] 课件设计必须满足内容科学.交互性好.界面简洁漂亮.使 ...

  7. python制作gif动画_实用的Python(2)利用Python制作gif动图

    一.简介 moviepy是一个专门用于视频剪辑制作的模块,可以自动化完成很多繁琐的视频剪辑处理工作,除了处理视频数据之外,moviepy中还内置了可以制作gif动图的功能,通过使用moviepy.ed ...

  8. python制作gif动画_使用Python代码制作GIF动态图

    使用Python PIL.Image 制作GIF图片: import PIL.Image 相关模块 img = Image.open(img_name) 打开图片 img.save(save_name ...

  9. python制作简单动画_用Tkinter Python制作简单动画

    我用Tkinter搜索了一个简单的动画代码,但是我发现了非常不同的例子,我无法理解正确的方法来编写动画. 这里我的工作代码显示一个简单的移动圆:import tkinter as tk import ...

  10. python制作图像数据集_详细图像数据集增强原理的python代码

    导读 在深度学习时代,数据的规模越大.质量越高,模型就能够拥有更好的泛化能力,数据直接决定了模型学习的上限.然而在实际工程中,采集的数据很难覆盖全部的场景,比如图像的光照条件,同一场景拍摄的图片可能由 ...

最新文章

  1. 创建Swap交换空间
  2. 人脸识别技术用于教育行业引争议
  3. 使用New Relic免费服务器监控
  4. python入门练习题-python入门-简单基础题练习
  5. ZOJ 3609 Modular Inverse(扩展欧几里得)题解
  6. myeclipse转maven项目
  7. 4399积分小游戏_分数提交规则
  8. CentOS 挂载 exfat 和 FAT32格式的U盘
  9. 分布式系统关注点(8)——99%的人都能看懂的「熔断」以及最佳实践
  10. Adobe Reader 的直接下载地址
  11. 带你了解什么叫大数据分析
  12. echart地图加载中国地图,可切换省市地图
  13. 服务器、存储和网络虚拟化的实现与应用
  14. python柱状图zzt_Python torch.diag方法代碼示例
  15. 乐MAX 乐视X900_官方线刷包_救砖包_解账户锁
  16. 守破离——编程的三种境界
  17. Python简单木马编写
  18. 怎样看服务器是什么操作系统,如何看服务器是什么操作系统
  19. Simio敏捷建模技术—Simio Templates
  20. Android问题解决:android.util.Base64.encode 导致签名不匹配 SignatureDoesNotMatch

热门文章

  1. Rayman的绝顶之路——Leetcode每日一题打卡19
  2. 信息产业部颁发计算机网络工程师查询,网络工程师证书查询验证网址及方法
  3. nature:2021年最值得关注的技术
  4. python爬虫论文总结与展望怎么写_论文总结与展望怎么写
  5. 2021-06-02使用Digispark(ATTINY85)制作一个Badusb
  6. 体系结构:Cache Coherence
  7. Win10如何使用BC3.1精简版
  8. PS使用:利用PS去除图片中的多余文字
  9. bootstrap treeview 多级联动check/uncheck
  10. NAACL 2022 | TAMT:通过下游任务无关掩码训练搜索可迁移的BERT子网络