r - 如何在 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)")
这主要按我想要的方式工作,除了不显示交点。
解决方案
这是一种使用手动计算交叉点的方法。在这种情况下,它依赖于计算的值之间存在精确的交集,但可以对其进行修改以找到最接近的匹配项。
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)")
推荐阅读
- java - Jib 和 Jib-Core 有什么区别?
- c# - 如何获得对象的旋转以匹配玩家的旋转
- c - 这些突出显示的行是实际代码的一部分吗?
- jquery - 我无法使用 Boostrap-3 和 Select2 将下拉列表与其他控件对齐
- javascript - 异步 useEffect 不适用于获取数据
- excel - 在 Excel 中使用 Power Queries 添加列,复制下一列的第一行
- java - maven聚合是否合并pom属性,如继承?
- javascript - 如何从具有大量属性的对象数组中获取“极简”对象数组
- php - 谷歌标签管理器在前端可见
- javascript - 如何在 reactJS 中渲染 JSON 文件