我正在尝试使用 R plotly 动画随着时间的推移连接点。
以下代码出现了几个问题:
df
)。add_segments
与 add_annotations
交换成箭头而不是线段,但是 frame
参数不起作用。请注意,删除 color
和 symbol
参数有助于第 2 点。
library(dplyr)
library(plotly)
set.seed(12)
df <- tibble(
day = rep(1:8, each = 10),
id = rep(paste0("ID", 1:10), 8),
infector = NA
) %>%
group_by(id) %>%
mutate(x = rnorm(1),
y = rnorm(1),
group = sample(c("A", "B", "C"), 1)) %>%
ungroup() %>%
mutate(
infector = case_when(
id == "ID2" & day >= 1 ~ "ID4",
id == "ID3" & day >= 2 ~ "ID4",
id == "ID1" & day >= 3 ~ "ID2",
id == "ID5" & day >= 3 ~ "ID3",
id == "ID6" & day >= 3 ~ "ID4",
id == "ID10" & day >= 4 ~ "ID2",
id == "ID9" & day >= 7 ~ "ID5"
)
)
infectors <- df %>% filter(day == 1 & id %in% .$infector) %>%
select(id, x, y, group) %>%
rename(infector.x = x,
infector.y = y,
infector_group = group)
df <- left_join(df, infectors, by = c("infector" = "id"))
pal <- c("A" = "blue", "B" = "green", "C" = "red")
plot_ly(df) %>%
add_markers(
x = ~ x,
y = ~ y,
frame = ~ day,
hoverinfo = "text",
text = ~ paste("ID:", id),
symbol = ~group,
color = ~group,
colors = pal
) %>%
add_segments(
x = ~infector.x,
xend = ~x,
y = ~infector.y,
yend = ~y,
color = ~infector_group,
colors = pal,
frame = ~day)