gpt4 book ai didi

r - gganimate:结合 transition_layers 和 geom_smooth

转载 作者:行者123 更新时间:2023-12-04 09:31:00 25 4
gpt4 key购买 nike

我如何将 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())

Current animation

最佳答案

这是一种复制数据然后过滤数据的方法,因此每个版本逐渐显示更多的年份。

library(dplyr); library(tidyr)

animate(
df %>%
count(year, wt = c, name = "c") %>% # Aggregate for each year's total
uncount(7, .id = "year_disp") %>% # Make 7 copies, one for each year
arrange(year_disp, year) %>%
mutate(year_disp = year_disp + min(df$year) - 1) %>%
filter(year <= year_disp) %>% # Only keep years up to "year_disp"
ggplot(aes(year, c)) +
geom_col(aes(group = year)) + # "group" here connects each year to itself between frames
geom_smooth(method = "lm", se = F) +
transition_states(year_disp) +
enter_drift(y_mod = -max(df$c)),
fps = 10, duration = 10,
width = 600, height = 500, renderer = gifski_renderer())

enter image description here

关于r - gganimate:结合 transition_layers 和 geom_smooth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58107079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com