Need Help on Using Dropdown to Filter

Hi, I am trying to create a scatterplot that uses dropdown for filtering.

library(plotly)    
plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length, mode = 'markers', visible = T) %>%
      layout(
        title = "Iris Dropdown",
        updatemenus = list(
          list(
            buttons = list(
              list(method = 'restyle',
                   args = list(iris$Species == "setosa", list(iris$Species =='setosa')),
                   label = "Setosa"),
              list(method = 'restyle',
                   args = list("iris$Species" == "versicolor", list(iris$Species =='versicolor')),
                   label = "Versicolor"),
              list(method = 'restyle',
                   args = list(iris$Species == 'virginica', list(iris$Species =='virginica')),
                   label = "Virginica")
              ))))

For the most part, it works except the dropdown. I did try reading through the examples (URL) but it was for changing a chart type. My understanding is that the key to dropdown is the args = list(x,y) . My understanding is the x is what to show, and y is the condition.

Please advise.

Hey @papuha

Consider using transforms https://plot.ly/r/#transforms with the dropdown:

library(plotly)    

p <- iris %>%
  plot_ly(
    type = 'scatter', 
    x = ~Sepal.Length, 
    y = ~Petal.Length,
    text = ~Species,
    hoverinfo = 'text',
    mode = 'markers', 
    transforms = list(
      list(
        type = 'filter',
        target = ~Species,
        operation = '=',
        value = unique(iris$Species)[1]
      )
  )) %>% layout(
    updatemenus = list(
      list(
        type = 'dropdown',
        active = 0,
        buttons = list(
          list(method = "restyle",
               args = list("transforms[0].value", unique(iris$Species)[1]),
               label = unique(iris$Species)[1]),
          list(method = "restyle",
               args = list("transforms[0].value", unique(iris$Species)[2]),
               label = unique(iris$Species)[2]),
          list(method = "restyle",
               args = list("transforms[0].value", unique(iris$Species)[3]),
               label = unique(iris$Species)[3])
        )
      )
    )
  )
2 Likes

Hi,

Could i use more than one transforms ?

Thanks

1 Like

To generalize for any number of Species, one could automatize the list before calling plotly:

plotly.buttons <- list()
labels=unique(iris$Species)
for (i in 1:length(labels)) {
  ply[[i]] = list(method = "restyle",
                  args = list("transforms[0].value", labels[i],
                  label = labels[i])
  )
}

Where then in your layout() function:

buttons = plotly.buttons