gpt4 book ai didi

r - gganimate 时间序列和两条线图

转载 作者:行者123 更新时间:2023-12-02 07:33:58 27 4
gpt4 key购买 nike

遵循源代码 Here 。我正在尝试用我的数据复制它。我有一个时间序列数据,我在 y 轴上绘制事件和非事件数字。这是我的示例数据结构:

df <- tibble::tribble(
~Date, ~active, ~non_active,
1, 848, 335,
2, 998, 280,
3, 1096, 308,
4, 1127, 274,
5, 1022, 313,
6, 973, 351,
7, 1131, 302,
8, 1165, 312,
9, 1159, 293,
10, 1192, 311,
11, 1221, 332,
12, 1075, 369,
13, 1056, 416,
14, 1219, 356,
15, 1240, 363,
16, 1270, 376,
17, 1302, 325,
18, 1292, 346,
19, 1104, 374,
20, 1084, 413,
21, 1257, 350,
22, 1306, 356,
23, 1318, 368,
24, 1380, 378,
25, 1350, 388,
26, 1163, 421,
27, 1158, 468,
28, 1368, 410,
29, 1429, 423,
30, 1514, 456,
31, 1564, 434
)

我对如何为下一行创建第二行跟踪器感到困惑。我在这里缺少什么?我们将不胜感激您的反馈/帮助!

我的代码:

library(gganimate)
library(dplyr)
library(tibbletime)
library(gifski)
library(ggplot2)
library(png)

p <- ggplot(df, aes(Date, active)) +
geom_line(aes(y = active)) +
geom_line(aes(y = non_active))+
geom_segment(aes(xend = 15, yend = active), linetype = 2, colour = 'blue') +
geom_segment(aes(xend = 15, yend = non_active), linetype = 2, colour = 'red') +
geom_point(size = 3) +
geom_text(aes(x = 15.1, label = active ), hjust = 0) +
transition_reveal(Date) +
# labs(title = "Date: {frame_time}") +
view_follow(fixed_y = TRUE)+
coord_cartesian(clip = 'off') +
labs(title = 'Active in Jan', y = 'Individual Active') +
enter_drift(x_mod = -1) + exit_drift(x_mod = 1) +
theme_bw() +
theme(
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black")
)+
# theme_minimal() +
theme(plot.margin = margin(5.5, 40, 5.5, 5.5))

animate(p, fps=5)

最佳答案

首先,需要将dfactivenon_active变量堆叠起来,然后创建一个组变量grp(具有两个类别的因素):

df2 <- data.frame(Date=rep(df$Date, 2), 
act_noact=c(df$active, df$non_active),
grp=rep(c("Active","Non active"), each=nrow(df)))

然后,您可以使用新的 df2 数据框和以下代码来绘制动画图:

p <- ggplot(df2, aes(x=Date, y=act_noact, group=grp)) +
geom_line() +
geom_segment(aes(xend=max(Date), yend = act_noact), linetype=2, colour='blue') +
geom_point(size = 3) +
geom_text(aes(x = max(Date)+.1, label = sprintf("%5.0f", act_noact)), hjust=0) +
transition_reveal(Date) +
view_follow(fixed_y = TRUE)+
coord_cartesian(clip = 'off') +
labs(title = 'Active in Jan', y = 'Individual Active') +
enter_drift(x_mod = -1) + exit_drift(x_mod = 1) +
theme_bw() +
theme(panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"),
plot.margin = margin(5.5, 40, 5.5, 5.5))

animate(p, fps=5)

enter image description here

关于r - gganimate 时间序列和两条线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54855334/

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