I am trying to animate a map of performance over time using the gganimate package. I am able to animate other ggplot
s that use geom_point()
but this one is throwing an error I cannot figure out.
I have made a workable example below that throws the same error:
library(tidyr)
library(ggplot2)
library(gganimate)
library(maps)
library(mapproj)
library(evaluate)
map <- map_data("world")
colnames(map)[1] <- "x"
colnames(map)[2] <- "y"
A1 <- data.frame(OrganisationID=c(1:10),x=rnorm(10) * 2 + 13,y= rnorm(10) + 48,`01 Jan 2020`=runif(10),"02 Jan 2020"=runif(10),
"03 Jan 2020"=runif(10),"04 Jan 2020"=runif(10),"05 Jan 2020"=runif(10),
"06 Jan 2020"=runif(10),"07 Jan 2020"=runif(10))
A1 <- gather(A1, Date, Performance, `X01.Jan.2020`:`X07.Jan.2020`, factor_key=TRUE)
A1$Date <- as.Date(A1$Date, format = "X%d.%b.%Y")
A1$Size <- sample(500:1000,70,T)
longitude_lim = sort(c(max(A1$x), min(A1$x)))
latitude_lim = sort(c(max(A1$y), min(A1$y)))
base_map <- ggplot() +
geom_polygon(data = map, aes(x=x, y = y, group = group), fill="grey", alpha=0.3) +
coord_fixed(xlim = longitude_lim, ylim = latitude_lim) +
labs(title = "Performance Regional") +
theme_bw() +
geom_point(aes(x=A1$x, y=A1$y, color=A1$Performance), alpha=0.9) +
scale_colour_gradient2(
low = "red",
mid = "#ffffcc",
high = "#33cc33",
midpoint = 0.85
)
# combine previous map lists, add points to map and animate
base_map
anim <- base_map +
transition_states(A1$Date, transition_length = 2,
state_length = 1)
anim
As you can see the base plot renders fine, but when I try to animate it I get
Error in order(ind) : argument 1 is not a vector
I don't know where to start untangling this as I do not have an object called 'ind' so I assume it's some process inside gganimate
. Any hints and tips are appreciated (also on a more efficient way to create my RepRoX)!
The issue is that you use two datasets, map
and A1
. To make your code work you have to "tell" gganimate which dataset to use for the animation by e.g. making A1
the global dataset by passing it to ggplot()
.
BTW: And as general rule when using ggplot2 don't assign variables to aesthetics via A1$...
:
base_map <- ggplot(data = A1) +
geom_polygon(aes(x=x, y = y, group = group), data = map, fill="grey", alpha=0.3) +
coord_fixed(xlim = longitude_lim, ylim = latitude_lim) +
labs(title = "Performance Regional") +
theme_bw() +
geom_point(aes(x=x, y=y, color=Performance), alpha=0.9) +
scale_colour_gradient2(
low = "red",
mid = "#ffffcc",
high = "#33cc33",
midpoint = 0.85
)
# combine previous map lists, add points to map and animate
base_map
anim <- base_map +
transition_states(Date, transition_length = 2,
state_length = 1)
anim