r - gganimate 时间序列和两条线图
问题描述
下面的源代码在这里。我正在尝试用我的数据复制它。我有一个时间序列的数据,我在 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)
解决方案
首先,您需要将active
和的non_active
变量堆叠起来df
,然后创建一个组变量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)
推荐阅读
- android - 折线角未正确连接
- java - 机器人类粘贴问题到腻子终端
- docker - docker login using -p 给出错误,当我像它推荐的那样切换到 --password-stdin 时仍然给出错误 - gitlab-ci
- azure-devops - 如何在 SonarCloud 和 TFS 之间同步问题
- angular - 无法从 httpclient json 请求角度正确读取数据
- sql - SQL批量数据重复检查
- java - Java .contains() 的行为不像我预期的那样
- android - 数组中的后退按钮导致应用程序崩溃
- angular - 如何获取和删除特定域的 HTTP-Only cookie?
- python-sphinx - 如何让 sphinx 不忽略 python 类方法的第一个参数?