首页 > 解决方案 > 如何使用 gganimate 使注释出现在特定帧上?

问题描述

我有一个时间序列折线图,其中包含特定日期的注释,我希望仅在动画到达该特定日期时出现,并一直持续到动画结束。下面是一个示例 - 我希望在该行到达 1945 时出现“二战结束”的行和文本:

在此处输入图像描述

library(tidyverse)
library(gganimate)
library(babynames)

# Keep only 1 name
don <- babynames %>% 
  dplyr::filter(name %in% c("Adolph")) 

# Plot
don %>%
  ggplot(aes(x = year, y = n, group=name)) +
  geom_line(aes (color = name)) +
  ggtitle("Popularity of American names Over Time") +
  ylab("Number of babies born") + 
  annotate ("text", x = 1945, y = 225, label = "End of WWII") +
  geom_segment(aes(x = 1945, y = 0,
                   xend = 1945, yend = 215),
               size = 0.25
  ) + 
  transition_reveal(year)

标签: rggplot2gganimate

解决方案


我的方法是将文本和段添加为仅在 1945 年出现的图层。到目前为止,我还没有成功使用这种方法transition_reveal,但它适用于transition_manual

annotate_table <- tibble(
  year = 1945,
  label = "End of WWII",
  text_height = 225,
  seg_top = 215
)
don %>%
  dplyr::filter(sex == "M") %>%  # presumably don't need to include the near-zero female Adolphs
  left_join(annotate_table) %>%
  ggplot(aes(x = year, y = n, group=name)) +
  geom_line(aes (color = name)) +
  ggtitle("Popularity of American names Over Time") +
  ylab("Number of babies born") + 
  geom_text(aes(label = label, y = text_height)) +
  geom_segment(aes(xend = year,  yend = seg_top), y = 0, size = 0.25) +
  transition_manual(year, cumulative = TRUE)

在此处输入图像描述


推荐阅读