手把手:如何用R制作动态图
原创
2015-11-02
大数据文摘
大数据文摘
大数据文摘作品,欢迎个人转发朋友圈,自媒体、媒体、机构转载务必申请授权,后台留言“机构名称+转载”,申请过授权的不必再次申请,只要按约定转载即可。 作者|顾运筠 如何用R制作动态的统计图呢?下面我们以“大数据文摘”国庆献礼的世界独立进程为例,手把手地教大家如何用R制作动态图。
从http://www./script/binary-releases.php网址下载相关的ImageMagic.exe。安装ImageMagic.exe。安装完成后启动Rstudio编写代码。
library(animation) library(maps)
由于国家很多,这里只选择几个国家,足够说明问题就可以了。 mtitle <-c("660","1668","1776","1788","1840","1867","1880","1948","1949","1950","1990") regList<-list(c("Japan"),c("UK"), c("USA"), c("Australia"),c("NewZealand"), c("Canada"), c("France"),c("Korea","South Korea"), c("China","Hungary"),c("Kuwait","India"),c("Russia","Germany","Yemen")) 对区域的列表采用了list形式,同一年成立的国家包含在一个regList[[k]]元素中,这样成立年份就和区域列表的元素一一对应了。
采用maps包中的map函数绘制成立区域。代码如下: #绘制空白世界地图 map("world") #添加独立区域,着色 map("world", region=reg,exact=FALSE, add=TRUE, fill=TRUE, col="pink")
#设定动画的时间间隔和帧数 oopt = ani.options(interval = 0.2, nmax =11) #生成动画 for (i in 1:ani.options("nmax")){ map("world") reg="" reg=regList[[1]] if (i>1) { for (k in 2:i) {reg =c(reg,regList[[k]])} } map("world", region=reg, exact=FALSE, add=TRUE, fill=TRUE,col="pink") title(mtitle[i]) #等待interval设置的时间长度 ani.pause() } #重载动画options ani.options(oopt)
oopt = ani.options(interval = 0.2, nmax =11) amax=ani.options("nmax") for (i in 1:amax) { map("world") for (k in 1:i) { map("world",region=regList[[k]], exact=FALSE, add=TRUE, fill=TRUE,col=rgb(k+15,16,16,max=3*amax)) } title(mtitle[i]) ani.pause() } ani.options(oopt)
library(maps) library(animation) #设定网页文件所在目录 setwd("…./webpage") mtitle <-c("660","1668","1776","1788","1840","1867","1880","1948","1949","1950","1990") regList <- list(c("Japan"),c("UK"), c("USA"), c("Australia"),c("NewZealand"), c("Canada"), c("France"), c("Korea","SouthKorea"),c("China","Hungary"),c("Kuwait","India"),c("Russia","Germany","Yemen")) saveHTML( { oopt = ani.options(interval = 0.2, nmax =11) amax=ani.options("nmax") for (i in 1:amax) { map("world") for (k in 1:i) { map("world",region=regList[[k]], exact=FALSE, add=TRUE, fill=TRUE,col=rgb(k+15,16,16,max=3*amax)) } title(mtitle[i]) ani.pause() } ani.options(oopt) },img.name = "map1", imgdir ="./img", htmlfile = "map.html", autobrowse =FALSE, title = "Demo of Country Independents")
library(maps) library(animation) #设定GIF 图片所在目录 setwd("…./") mtitle <-c("660","1668","1776","1788","1840","1867","1880","1948","1949","1950","1990") regList <- list(c("Japan"),c("UK"), c("USA"), c("Australia"),c("NewZealand"), c("Canada"), c("France"),c("Korea","SouthKorea"),c("China","Hungary"),c("Kuwait","India"),c("Russia","Germany","Yemen")) saveGIF( { oopt = ani.options(interval = 0.2, nmax =11) amax=ani.options("nmax") for (i in 1:amax) { map("world") for (k in 1:i) { map("world",region=regList[[k]], exact=FALSE, add=TRUE, fill=TRUE,col=rgb(k+15,16,16,max=3*amax)) } title(mtitle[i]) ani.pause() } ani.options(oopt) },movie.name="demo.gif",img.name="map1") 粗略的就介绍到这里了。还可以生成flash等其他的动画,不一一列出了。祝大家工作、生活愉快! |
|