通过下拉菜单更新 r plot_ly 图表

Updating r plot_ly chart by drop down menu

我有一个简单的图表示例,并在图表中发现了非常有趣的下拉菜单功能 (link)。

当我在非常简单的 mtcars 示例上尝试该操作时,在下拉菜单中切换项目时似乎没有更新。

p <- plot_ly(df, x = mtcars$mpg, y = mtcars$disp, mode = "markers", name = "A", visible = T) %>%
  layout(
    title = "Drop down menus - Styling",
    xaxis = list(domain = c(0.1, 1)),
    yaxis = list(title = "y"),
    updatemenus = list(
      list(
        y = 0.8,
        buttons = list(
          list(method = "restyle",
               args = list("x", mtcars$mpg),
               label = "mpg"),
          list(method = "restyle",
               args = list("x", mtcars$disp),
               label = "disp"))),
      list(
        y = 0.7,
        buttons = list(
          list(method = "restyle",
               args = list("y", mtcars$hp),
               label = "hp"),
          list(method = "restyle",
               args = list("y", mtcars$wt),
               label = "wt")))
))

p

我做错了什么。拜托,你能帮我吗?非常感谢。

您的代码有一些语法错误,将其更改为这样的代码应该可以正常工作:

p <- plot_ly(mtcars, x= ~mpg, y= ~hp, type="scatter", mode = "markers")
p %>% layout(
  yaxis = list(title = "y"),
  xaxis = list(title = "x"),
  updatemenus = list(
    list(
      y = 0.8,
      buttons = list(
        list(method = "animate",
             args = list("x", list(~mpg)),
             label = "mpg"),
        list(method = "animate",
             args = list("x", list(~disp)),
             label = "disp"))),
    list(
      y = 0.7,
      buttons = list(
        list(method = "animate",
             args = list("y", list(~hp)),
             label = "hp"),
        list(method = "animate",
             args = list("y", list(~wt)),
             label = "wt")))
))

版本:plotly_4.5.2