Search code examples
rplotlyr-plotly

Plotly update nested argument via updatemenus


I would like to create a dropdown menu using updatemenus from R Plotly to be able to change the source image in a plot.

This is what I have done so far, without success:

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")
        )
      )
    )
  )

enter image description here

What am I missing?


Solution

  • There is probably more than one way to do this, but this works. For layout updates, you're usually going to use the method relayout. You need to provide all of the information, as well (i.e., x, y, xref, etc.).

    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)))
            ))))
    

    There are a few method options for updatemenus. You can read more about that here.

    enter image description here