Animate points and regression line along date with gganimate()

做~自己de王妃 提交于 2020-04-16 03:19:03

问题


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!


回答1:


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)

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:

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/



来源:https://stackoverflow.com/questions/60856938/animate-points-and-regression-line-along-date-with-gganimate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!