Will M
Will M

Reputation: 812

Animate points and regression line along date with gganimate()

I'm trying to animate points and a loess regression line, so they appear/are revealed simultaneously along year, but I'm returned with an error, as described below with a reprex.

This would be the ideal animation: https://user-images.githubusercontent.com/1775316/49728400-f0ba1b80-fc72-11e8-86c5-71ed84b247db.gif Unfortunately, the thread where I found this did not have the accompanying code.

See my reprex problem here:

#Animate points and regression loess line along with dates at the same time
library(MASS) #for phones reprex dataset
phones <- data.frame(phones) #Prepare reprex data
library(ggplot2) #for plotting
library(gganimate) #for animation

#Animation
ggplot(phones, aes(x = year, y = calls)) +
  geom_point() + geom_smooth(method = "loess", colour = "orange",
                             se = FALSE) +
  transition_time(year) + shadow_mark() + ease_aes("linear")

This returns the error:

Error in `$<-.data.frame`(`*tmp*`, "group", value = "") : 
  replacement has 1 row, data has 0

Some have suggested I insert aes(group = year) in geom_smooth(), but that returns the same error.

Thanks for all your help in advance!

Upvotes: 2

Views: 1093

Answers (1)

Nova
Nova

Reputation: 5861

Try first calculating the value of the loess line at each of your data points, then graphing that as you go. To make the line smoother, you can predict the values on a dataframe that has more values for "year". You'll need to ensure you have the transformr library. Thanks to @paqmo for the suggestion to use transition_reveal and the OP for the group hint!

library(transformr)
smooth_vals = predict(loess(calls~year,phones))
phones$smooth_vals <- smooth_vals


#Animation
anim <- ggplot(phones, aes(x = year, y = calls)) +
  geom_point(aes(group = seq_along(year))) + 
  geom_line(aes(y = smooth_vals), colour = "orange") +
  transition_reveal(year) + 
  #shadow_mark() + 
  ease_aes("linear")

animate(anim, fps = 10, duration = 2)

the final animation

If you want to alter the shape of the loess line, just add a span argument to the loess function:

smooth_vals = predict(loess(calls~year,phones, span = 1))
phones$smooth_vals <- smooth_vals

Here's what that one looks like - notice the tighter fit to the points:

graph with points and lines appearing but with closer loess fit

This site is a great resource for gganimate, it helped me come up with this solution: https://www.datanovia.com/en/blog/gganimate-how-to-create-plots-with-beautiful-animation-in-r/

Upvotes: 5

Related Questions