Plotly chart with dynamic dropdown list

I have created several plotly charts using dropdown list filters to filter the dataset. This works fine but the number of items in the dropdown list is hardcoded. What if the data is updated and another option is available to filter the data. For example, see the code below. Is there a dynamic way of assigning the list to the buttons just in case a 4th option becomes available which can automatically be included in the dropdown list? Some form of for iteration or apply function might be needed?

Example code can be seen in the followed link
https://community.plotly.com/t/need-help-on-using-dropdown-to-filter/6596

1 Like

Hi, I encountered the same problem, generating a dynamic dropdown list based on user data selection. My solution creates a list that replicates the structure of the “button” specification in the “updatemenus” list in the “layout” code for the chart:
This is an example of the static dropdown (with 4 entries in this case):

                      ... updatemenus = list(
                         list(
                           type = 'dropdown',
                           active = 0,
                           buttons = list(
                             list(method = "restyle",
                                  args = list("transforms[0].value", unique(f.place$geoname)[1]),
                                  label = unique(f.place$geoname)[1]),
                             list(method = "restyle",
                                  args = list("transforms[0].value", unique(f.place$geoname)[2]),
                                  label = unique(f.place$geoname)[2]),
                                  args = list("transforms[0].value", unique(f.place$geoname)[3]),
                                  label = unique(f.place$geoname)[3]),
                             list(method = "restyle",
                                  args = list("transforms[0].value", unique(f.place$geoname)[4]),
                                  label = unique(f.place$geoname)[4])
))

My solution replicates the list structure of the “buttons” “NameList” is a unique list of labels, in my case taken from a data frame:

genDropdown <- function(NameList) {
    outlist <- list(list(
      method = "restyle", 
      args=list("transforms[0].value", NameList[1]),
      label = NameList[1]
    ))
      
    for(i in 2:length(NameList)) {
       item <- list(list(
        method = "restyle", 
        args=list("transforms[0].value", NameList[i]),
        label = NameList[i]
        ))
       outlist <- c(outlist,item)
    }
 
    return(outlist)
  }

and the new “updatemenus” specification is:

... updatemenus = list(
                      list(
                        type = 'dropdown',
                        active = 0,
                        buttons = genDropdown(txtNames)
                      ))

This is all done with R plotly (I understand the approach with dash is more straight forward, so it goes).
HTH
AB