提问人:user3466328 提问时间:12/22/2014 最后编辑:Ujjwaluser3466328 更新时间:1/1/2015 访问量:1377
使用 ggplot2、ggmap、plyr 和 animate 创建时间序列世界交通动画
Create Time Series World Traffic Animation Using ggplot2, ggmap, plyr and animate
问:
我正在尝试使用 ddply 内部的 ggplot 调用作为 animate 包的输入,以创建时间序列世界交通动画。这是我的代码;
library("ggmap")
library(maptools)
library(maps)
library(plyr)
......
#create map which we will then populate
mapWorld <- borders("world", colour="gray50", fill="gray50") # create a layer of borders
plots<-dlply(b, .(b$day), function(b) ggplot(b, aes(x=lon, y=lat, color=country,
group=country)) + mapWorld + geom_point(data=b, aes(x=lon, y=lat,
size=counts/100))+scale_size_identity(trans="sqrt")+guides(colour = guide_legend(override.aes
= list(size=3))))
library(animation)
#ani.options(interval=.05)
animation::saveVideo(plots, interval=0.5, video.name="world_animation.gif")
b 是包含日期的数据框,例如。01/01/2014,lon eg 73, lat e.g. 52, 国家 e.g. US, 计数 e.g. 25.
但是,我不断收到以下错误:
[image2 @ 0x7fd96c817000] Could find no file with path 'Rplot%d.png' and index in the range 0-4
Rplot%d.png: No such file or directory
有什么建议吗?
谢谢!
答:
4赞
user4359255
12/23/2014
#1
使用 animation、ggmap 和 ggplot2 包,我可以创建世界城市的时间序列动画。动画是使用动画包中的 saveHTML 函数创建的,可以在浏览器中查看。
library(ggmap)
library(ggplot2)
library(animation)
#Create a data frame
countryDF<- data.frame(c("united states", "france", "india"))
colnames(countryDF) <- "countryname"
LatLon <- c(apply(countryDF, 1, geocode))
LatLonDF <- do.call(rbind.data.frame, LatLon)
countryLatLonDF <- cbind(countryDF, LatLonDF)
countryLatLonDF[,"myDate"]<- c("02/12/13", "03/16/14", "01/10/13")
countryLatLonDF$myDate <- as.Date(countryLatLonDF$myDate , "%m/%d/%y")
countryLatLonDF["counts"] <- as.numeric(c(10,20,30))
#Sort countryLatLonDF based on dates
countryLatLonDF <- countryLatLonDF[ order(countryLatLonDF[,4]), ]
#Create animation in HTML file
saveHTML({
for (i in 1:nrow(countryLatLonDF))
{
#Get the map
myMap <- ggmap(get_map(location = c(lat=0, lon=0), color="color",source="google", maptype="terrain", zoom=2))
myMap <- myMap + geom_point(data = countryLatLonDF[i,], aes(x = lon, y = lat, color = countryname, alpha = 0.5, fill = "red"), size = 5, shape = 21) + geom_text(data = countryLatLonDF[i,], aes(x = lon, y = lat, label = countryname), size = 3, vjust = 0, hjust = -0.1, color = "blue") + scale_colour_discrete(name = "countryname")
print(myMap)
}
}, img.name = "anim_plot", imgdir = "anim_dir", htmlfile = "anim.html", autobrowse = FALSE, title = "Country animation", verbose =FALSE, interval = 2)
graphics.off()
HTML 动画文件将保存在工作目录中。您可以使用 setwd() 设置工作目录。希望这会有所帮助。
评论
traceback()
getwd()
sessionInfo()