gganimate时间序列和两线图

时间:2019-02-24 18:52:29

标签: r ggplot2 gganimate

跟随源代码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)

1 个答案:

答案 0 :(得分:2)

首先,您需要堆叠active的{​​{1}}和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

enter image description here