通过 updatemenus 更新嵌套参数

Plotly update nested argument via updatemenus

我想使用 R Plotly 中的 updatemenus 创建一个下拉菜单,以便能够更改绘图中的源图像。

这是我到目前为止所做的,但没有成功:

library(plotly)
library(magrittr)

img1 <- "https://www.gravatar.com/avatar/dc04a25fbabbffc1f1b7c6a3362bfae4?s=256&d=identicon&r=PG"
img2 <- "https://www.gravatar.com/avatar/bc680ed8d2555accacebc0fe2d8c9691?s=256&d=identicon&r=PG"

plot_ly(x = 1:5, y = 1:5, type = 'scatter', mode = 'markers') %>% 
  layout(
    images = list(
      list(
        source =  img1,
        xref = "x",
        yref = "y",
        x = 3,
        y = 4,
        sizex = 2,
        sizey = 2
      )
    ),
    updatemenus = list(
      list(
        y = 1,
        buttons = list(
          list(method = "restyle",
               args = list(list(images = list(list(source = img1)))),
               label = "img1"),
          list(method = "restyle",
               args = list(list(images = list(list(source = img2)))),
               label = "img2")
        )
      )
    )
  )

我错过了什么?

可能有不止一种方法可以做到这一点,但这行得通。对于布局更新,您通常会使用 relayout 方法。您还需要提供所有信息(即 xyxref 等)。

library(plotly)

img1 <- "https://www.gravatar.com/avatar/dc04a25fbabbffc1f1b7c6a3362bfae4?s=256&d=identicon&r=PG"
img2 <- "https://www.gravatar.com/avatar/bc680ed8d2555accacebc0fe2d8c9691?s=256&d=identicon&r=PG"

imgOne = list( # create image expectations
  list(
    source =  img1,
    xref = "x", yref = "y",
    x = 3, y = 4,
    sizex = 2, sizey = 2))

imgTwo = list( # create image expectations
  list(
    source =  img2,
    xref = "x", yref = "y",
    x = 3, y = 4,
    sizex = 2, sizey = 2))

plot_ly(x = 1:5, y = 1:5, type = 'scatter', mode = 'markers') %>% 
  layout(
    images = imgOne,
    updatemenus = list(
      list(
        y = 1,
        active = 0,
        buttons = list(
          list(label = "None",
               method = "relayout",
               args = list(list(images = c()))),
          list(label = "img1",
               method = "relayout",
               args = list(list(images = imgOne))),
          list(label = "img2",
               method = "relayout",
               args = list(list(images = imgTwo)))
        ))))

updatemenus 有几个 method 选项。 You can read more about that here.