使用带有R中的地图数据的ggplot创建动画

时间:2013-11-11 23:34:55

标签: r animation ggplot2

我有一个州每个县的每周数据。我想创建一个循环遍历每周的动画,显示绘制到地图上的数据,颜色表示强度和/或上周的变化。

library(ggplot2); library(animation); library(maps); library(plyr)

county <- map_data("county")

wy <- county[county$region =="wyoming",]

l = length((wy$subregion))
#Add random variales
wy <- mutate(wy, a = runif(length(region)), 
             b = runif(length(region)), 
             c= runif(length(region)))

test <- function(j){             
ggplot(wy, aes(long, lat, group = group))+ 
  geom_path() + 
  geom_polygon(aes_string(fill=j))
}

test("c")
test("b")


v = c("a","b","c"))

oopt <- animation::ani.options(interval = 0.1)

FUN2 <- function() {
  lapply(v, function(i) {
    test(i)
    animation::ani.pause()
  })
}
FUN2()

saveHTML(FUN2(), autoplay = FALSE, loop = FALSE, verbose = FALSE, outdir = "images/animate/new",
 single.opts = "'controls': ['first', 'previous', 'play', 'next', 'last', 'loop', 'speed'], 'delayMin': 0")

上一次函数调用有什么问题?

1 个答案:

答案 0 :(得分:5)

library(ggplot2); library(animation); library(maps); library(plyr)

county <- map_data("county")

wy <- county[county$region =="wyoming",]

l = length((wy$subregion))
#Add random variales
wy <- mutate(wy, a = runif(length(region)), 
             b = runif(length(region)), 
             c= runif(length(region)))

test <- function(j){             
  ggplot(wy, aes(long, lat, group = group))+ 
    geom_path() + 
    geom_polygon(aes_string(fill=j))
}

test("c")
test("b")

wy$1 <- wy$a

oopt <- animation::ani.options(interval = 0.1)

FUN2 <- function() {
  v = c("a","b","c")
  lapply(v, function(i) {
    print(test(i))
    ani.pause()
  })
}
FUN2()

saveHTML(FUN2(), autoplay = FALSE, loop = FALSE, verbose = FALSE, outdir = "images/animate/new",
         single.opts = "'controls': ['first', 'previous', 'play', 'next', 'last', 'loop', 'speed'], 'delayMin': 0")

在第二个功能中缺少print(test(i))