Create animation with ggplot with map data in R

2019-08-01 00:42发布

问题:

I have weekly data for each county in a state. I would like to create an animation that loops through each week showing the data plotted onto a map with colours indicating intensity and/or change from previous week.

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

What is wrong with the last function call?

回答1:

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

Missing the print(test(i)) in the second function.