Wil*_*iam 2 animation regression r ggplot2 gganimate
我正在尝试对点和黄土回归线进行动画处理,以便它们在一年中同时出现/显示,但我返回了一个错误,如下所述,带有 reprex。
这将是理想的动画:https://user-images.githubusercontent.com/1775316/49728400-f0ba1b80-fc72-11e8-86c5-71ed84b247db.gif 不幸的是,我发现这个的线程没有附带的代码。
在这里查看我的 reprex 问题:
#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")
Run Code Online (Sandbox Code Playgroud)
这会返回错误:
Error in `$<-.data.frame`(`*tmp*`, "group", value = "") :
replacement has 1 row, data has 0
Run Code Online (Sandbox Code Playgroud)
有些人建议我插入aes(group = year)in geom_smooth(),但这会返回相同的错误。
提前感谢您的所有帮助!
首先尝试计算每个数据点处的黄土线值,然后将其绘制成图表。为了使线条更平滑,您可以预测具有更多“年份”值的数据帧上的值。您需要确保您拥有该transformr库。感谢@paqmo 提出使用transition_reveal 的建议和组提示的OP!
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)
Run Code Online (Sandbox Code Playgroud)
如果你想改变黄土线的形状,只需span向黄土函数添加一个参数:
smooth_vals = predict(loess(calls~year,phones, span = 1))
phones$smooth_vals <- smooth_vals
Run Code Online (Sandbox Code Playgroud)
这就是它的样子 - 请注意这些点的配合更紧密:
这个网站是一个很好的资源gganimate,它帮助我想出了这个解决方案:
https ://www.datanovia.com/en/blog/gganimate-how-to-create-plots-with-beautiful-animation-in-r /