r-plotly 筛选按钮显示所有数据

And*_*ile 5 r r-plotly

我正在尝试使用 r-plotly 制作交互式图表。我希望有一个按钮可以按数据中指定的组进行过滤。在下面的示例中,该按钮用于将数据过滤到组 1 和组 2,但“所有组”按钮不会显示所有数据。有人有建议吗?

df <- tibble(x = c(1, 4, 2, 7), y = c(3, 1, 8, 4), group = c(2, 1, 1, 2))

fig <- plot_ly(data = df, type = "scatter", mode = "markers") %>%
  add_trace(type = "scatter", mode = "markers", x=~x, y=~y,
            transforms = list(
              list(
                type = "filter",
                target = ~group,
                operation = 'in',
                value = unique(df$group)
              )
            )
  ) %>%
  layout(
    updatemenus = list(
      list(
        type = 'dropdown',
        active = 0,
        buttons = list(
          list(method = "restyle",
               args = list("transforms[0].value", unique(df$group)[2]),
               label = "Group 1"),
          list(method = "restyle",
               args = list("transforms[0].value", unique(df$group)[1]),
               label = "Group 2"),
          list(method = "restyle",
               args = list("transforms[0].value", unique(df$group)),
               label = "All groups")
        )
      )
    )
  )
fig
Run Code Online (Sandbox Code Playgroud)

小智 0

这花了我很长时间才弄清楚。您需要在按钮内进行'{}', 和操作:list(unique(df$group))

df <- tibble(x = c(1, 4, 2, 7), y = c(3, 1, 8, 4), group = c(2, 1, 1, 2))

fig <- plot_ly(data = df, type = "scatter", mode = "markers") %>%
  add_trace(type = "scatter", mode = "markers", x=~x, y=~y,
            transforms = list(
              list(
                type = "filter",
                target = ~group,
                operation = '{}',
                value = unique(df$group)
              )
            )
  ) %>%
  layout(
    updatemenus = list(
      list(
        type = 'dropdown',
        active = 2,
        buttons = list(
          list(method = "restyle",
               args = list("transforms[0].value", unique(df$group)[2]),
               label = "Group 1"),
          list(method = "restyle",
               args = list("transforms[0].value", unique(df$group)[1]),
               label = "Group 2"),
          list(method = "restyle",
               args = list("transforms[0].value", list(unique(df$group))),
               label = "All groups")
        )
      )
    )
  )
fig
Run Code Online (Sandbox Code Playgroud)