使用gganimate()沿日期对点和回归线进行动画处理 [英] Animate points and regression line along date with gganimate()

查看:204
本文介绍了使用gganimate()沿日期对点和回归线进行动画处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为点和一条黄土回归线设置动画,因此它们会在一年中同时显示/显示出来,但是我却返回了一个错误,如下所述(带有reprex)。



这将是理想的动画:



如果要更改黄土线的形状,只需在黄土函数中添加 span 参数:

  smooth_vals =预测(黄土(通话〜年,电话,跨度= 1))
手机$ smooth_vals<-平滑_vals

这是一个什么样子-注意要紧的点:





gganimate 的重要资源,它帮助我提出了以下解决方案:
> https://www.datanovia.com/en/blog/gganimate-how用r /


创建漂亮的动画图

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!

解决方案

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/

这篇关于使用gganimate()沿日期对点和回归线进行动画处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆