首页 > 解决方案 > 如何在 gganimate 上添加交点?

问题描述

我正在设置两条曲线的动画,因为其中一条曲线的斜率发生变化,我想在动画中的每个状态下显示变化的交点。我知道交点在哪里,但不知道如何将它们包含在每个州的图中。

我尝试为每个状态的交点添加一个单独的 transition_manual ,但它只会显示这一点,而不是第二个转换。

library(tidyverse)
library(gganimate)

tbl <- tibble(x = seq(-8, 8, by = .01),
             A_1 = 4*x,
             B_1 = x^2,
             A_2 = 3*x,
             B_2 = x^2,
             A_3 = 2*x,
             B_3 = x^2,
             A_4 = x,
             B_4 = x^2,
             A_5 = 0*x,
             B_5 = x^2) %>%
 gather(group, density, A_1:B_5) %>%
 separate(group, c("group", "type"), sep = "_") %>%
 mutate(type = as.numeric(type)) %>%
 mutate(Title = case_when(
   type == 1 ~ "A = 0, B = 4",
   type == 2 ~ "A = 0, B = 3",
   type == 3 ~ "A = 0, B = 2",
   type == 4 ~ "A = 0, B = 1",
   TRUE ~ "A = B = 0"
 ))


  ggplot(tbl) + geom_line(mapping = aes(x = x, y = density, colour = group)) +
 transition_states(Title, transition_length = .5, state_length = 2, wrap = TRUE) +
 labs(title = '{closest_state}') + ylab("f(x)") 

这主要按我想要的方式工作,除了不显示交点。

标签: rggplot2dplyrtidyversegganimate

解决方案


这是一种使用手动计算交叉点的方法。在这种情况下,它依赖于计算的值之间存在精确的交集,但可以对其进行修改以找到最接近的匹配项。

intersects <- tbl %>%
  spread(group, density) %>%
  mutate(var = A - B) %>%
  # group_by(Title) %>%       # Alternative: find top 2 by Title
  # top_n(2, -abs(var)) %>%   # Alternative: find top 2 by Title 
  #                           # (Won't work in some edge cases...)
  filter(var == 0) %>%  # presumes exact intersection exists in rows
  mutate(intersect = TRUE) %>%
  select(x, type, Title, density = A, intersect)

tbl2 <- tbl %>%
  left_join(intersects)

ggplot(tbl2, aes(x, density, colour = group)) + 
  geom_line() +
  geom_point(data = tbl2 %>% filter(intersect)) +
  transition_states(Title, transition_length = .5, state_length = 2, wrap = TRUE) +
  labs(title = '{closest_state}') + ylab("f(x)") 

在此处输入图像描述


推荐阅读