如何使用`gganimate`为轴标签设置动画?

时间:2019-04-27 08:32:29

标签: r ggplot2 gganimate

实际上我很惊讶地发现我无法快速找到有关如何执行此操作的指南。这是一个示例:

library(ggplot2)
library(gganimate)
library(data.table)
library(magrittr)

dt <- lapply(seq(10), function(i){
    mean = i
    label = paste0("T = ", i)
    dt = data.table(x = seq(0, 50, length.out = 100))
    set(dt, j = "y", value = dt[, dlnorm(x, meanlog = log(mean), sdlog = 0.2)])
    set(dt, j = "frameN", value = i)
    return(dt)
}) %>% rbindlist

print(dt)

p <- ggplot(dt, aes(x = x, y = y)) +
  geom_line() +
  scale_x_continuous(name = "x", breaks = c(0, 1)) +
  transition_manual(frameN)

animate(p)

我希望breaks的{​​{1}}和labels遵循我自己的定义:

scale_x_continuous

然后

  • arr_breaks <- c(1, 3, 2, 4, 3, 5, 4, 6, 5, 7) arr_labels <- paste0(seq(10, 100, 10), " kg") for frame 1
  • breaks = arr_breaks[1], labels = arr_labels[1]用于第2帧

...

  • breaks = arr_breaks[2], labels = arr_labels[2]适用于第10帧

无论我怎么做,我都会出错。有想法吗?

1 个答案:

答案 0 :(得分:0)

正如@ z-lin所指出的,据我所知,目前尚未设置gganimate来对具有不同间隔的比例进行动画处理。该效果可以使用geoms进行近似估算,并且通过做更多的工作,您可能可以使视觉效果与变化的比例完全匹配。

breaks_df <- data.frame(

frameN = c(1:10),
  arr_breaks = c(1, 3, 2, 4, 3, 5, 4, 6, 5, 7),
  arr_labels = paste0(seq(10, 100, 10), " kg")
)

p <- ggplot(dt, aes(x = x, y = y)) +
  geom_segment(data = breaks_df, color = "white",
               aes(x = arr_breaks, xend = arr_breaks,
                   y = -Inf, yend = Inf)) +
  geom_text(data = breaks_df, vjust = 3, size = 3.5, color = "gray30",
            aes(x = arr_breaks, y = 0, label = arr_labels)) +
  geom_line() +
  scale_x_continuous(name = "x", breaks = c(0)) +
  coord_cartesian(clip = "off") +
  transition_manual(frameN)
animate(p, width = 600, height = 250)

enter image description here