Black Lives Matter. Please consider donating to Black Girls Code today.
Dash Enterprise delivers an incredible 21x cost savings 💸Download the e-book!

Change data with dropdown event in a scatterplot

I am trying to change the data displayed in a scatterplot using a dropdown event. I am using R in RStudio on Windows 7. The data are not important at this point and are merely placeholders for more complex changes…

# read in master file dataset
df <- read.csv('master_file_dataset.csv')

data <- df[1:1000,]
data2 <- df[1:100,]

# test plotly
p <- plot_ly(data = data, type = 'scatter', mode = 'markers',
             x = ~Age, y = ~Ending.Compensation, visible=F) %>%

    add_trace(data = data2, x = ~Age, y = ~Ending.Compensation, visible=F) %<%

    add_markers(marker = list(line = list(color = "black", width = 1))) %>%

    layout(
        title = "cluster selector example",
        xaxis = list(title = 'Age'),
        yaxis = list(title = "Salary"),
    
        updatemenus = list(
            list(
                yanchor = 'auto',
                buttons = list(
                
                    list(method = "update",
                         args = list("visible", list(TRUE, FALSE)),
                         label = 'data'),
                
                    list(method = "update",
                         args = list("visible", list(TRUE, FALSE)),
                         label = 'data2')
        
        ))))

I get this error…

Error in eval(expr, envir, enclos) : could not find function "%<%"

I am not sure how to get past this error and ultimately how to change the data using the dropdown event. Thanks for your help
Ben

To get rid of the this error…

Error in eval(expr, envir, enclos) : could not find function "%<%"

change the add_trace line of code to not inherit information from the plot_ly function…

    add_trace(data = data2, x = ~Age, y = ~Ending.Compensation, 
              inherit = F, visible=F, type = 'scatter', mode = 'markers') %>%

Even with this part solved, I still can’t change data using dropdown event.

apparently you need to download the macgrittr package to support the %<% function.
Even so, this doesn’t help with the error: could not find function plot_ly

data <- runif(100,0,1000)
data2 <- runif(100,0,1000)

p <- plot_ly() %>%
  add_trace(type = 'scatter', mode = 'markers',
             y = data, visible=T, marker = list(color = 'blue'))  %>%
  add_trace(type = 'scatter', mode = 'markers',
            y = data2, visible=F, marker = list(color = 'red')) %>%
  layout(
    updatemenus = list(
      list(
        yanchor = 'auto',
        buttons = list(
          list(method = "restyle",
               args = list("visible", list(T, F)),
               label = 'data'),
          
          list(method = "restyle",
               args = list("visible", list(F,T)),
               label = 'data2')
        ))))