连接点的片段在 R 绘图动画中消失

问题描述 投票:0回答:0

我正在尝试使用 R plotly 动画随着时间的推移连接点。

以下代码出现了几个问题:

  1. 段从一个连接浮动到另一个。
  2. 尽管连接在连续几天仍然存在,但这些段从一天到另一天消失(见 df)。
  3. 我试图将 add_segmentsadd_annotations 交换成箭头而不是线段,但是 frame 参数不起作用。

请注意,删除 colorsymbol 参数有助于第 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)

r plotly
© www.soinside.com 2019 - 2024. All rights reserved.