【发布时间】:2020-01-26 03:48:31
【问题描述】:
如何将 geom_smooth(method = "lm) 函数与 gganimate() 的 transition_layers 结合起来,这样,随着各个条形向上漂移/增长,geom_smooth 的线性线出现,如下所示:Example of desired appearance of geom_smooth line 唯一不同之处在于,在我的情况下,当线条出现时,条形将向上漂移,而不是点。
当前的条形图运行良好,通过向上漂移出现,通过使用 gganimate 的 transition_layers 函数成为可能。
但是,我不知道如何添加 geom_smooth 线,所以它会随着条形向上增长而出现。现在,该行出现在末尾,如下所示。
请参阅下面的动画当前外观。
这是我的问题的简单表述:
#Df for reprex
library(ggplot2)
library(tidyverse)
year <- as.numeric(c(1996:2002,
1996:2002,
1996:2002))
c <- c(39, 40, 67, 80, 30, 140, 90, 23, 100, 123,
140, 1, 2, 1, 13, 3, 3, 30, 1, 3, 3)
df <- data.frame(year, c) %>%
select(year, c) %>%
arrange(year)
#Static plot
(static_plot <- ggplot(data = df) +
geom_bar(data = df %>% filter(year == 1996), stat="identity", position ="stack",
aes(x = year, y = c)) +
geom_bar(data = df %>% filter(year == 1997), stat="identity", position ="stack",
aes(x = year, y = c)) +
geom_bar(data = df %>% filter(year == 1998), stat="identity", position ="stack",
aes(x = year, y = c)) +
geom_bar(data = df %>% filter(year == 1999), stat="identity", position ="stack",
aes(x = year, y = c)) +
geom_bar(data = df %>% filter(year == 2000), stat="identity", position ="stack",
aes(x = year, y = c)) +
geom_bar(data = df %>% filter(year == 2001), stat="identity", position ="stack",
aes(x = year, y = c)) +
geom_bar(data = df %>% filter(year == 2002), stat="identity", position ="stack",
aes(x = year, y = c)) +
labs(y = "year",
x = "c",
title = "Reprex") +
geom_smooth(df, mapping = aes(x = year, y = c), method = "lm",
colour = "black", se = F)
)
#Animation
library(gganimate)
anim <- static_plot +
transition_layers(layer_length = 1, transition_length = 1) +
enter_drift(x_mod = 0, y_mod = -max(df$c))
animate(anim, fps = 10, duration = 10,
width = 600, height = 500, renderer = gifski_renderer())
【问题讨论】:
-
已找到相关答案。但是,这并不能使回归线看起来平滑。我仍然非常感谢一个包含回归线以出现在一个平滑过渡中的答案,就像上面问题中的示例一样。此解决方案使该行出现在几个不同的块中:community.rstudio.com/t/…
-
在第一个视图中,我会说,鉴于当前的解决方案,“平滑度”与您可以添加到绘图中的条形数量成比例。请注意,在链接的“平滑”图表(以及您的图表)中,该线会针对 x 轴/横坐标上的每个新值进行更新,...您是否有可用的月度数据/您能否将其拆分为更多“酒吧”?
-
我相信我的解决方案可以实现您的目标,即使回归线看起来平滑、平滑过渡并根据每个点的可用数据进行移动。如果这不是您的想法,请告诉我。
-
干杯!我刚刚验证了你的答案。你知道如何改变你的动画,让回归线不会每一步都改变,而是基于完整的数据集吗?
-
您希望回归线从其最终位置开始并在数据填充时停留在那里吗?
标签: r animation ggplot2 plot gganimate