mary
mary

Reputation: 51

Dropdown menu for changing the color attribute of data in scatter plot (Plotly R)

I am trying to create a plotly graph with selectable color attribute so that passing the selected categorical data column as color variable, it changes the color of marks as well as the legend of my scatter plot.

Here is the Example:

df <- data.frame(x = runif(200), y = runif(200), 
                 z = sample(c("a", "b", "c"), 200, replace=TRUE),
                 w = sample(c("d", "e", "f",'g'), 200, replace=TRUE))
p <- plot_ly(df, x = ~x)%>%
  add_markers(y = ~y, color = ~z,visible=T)%>%
  layout(
    title = "Drop down menus - color",
    xaxis = list(domain = c(0.1, 1)),
    yaxis = list(title = "y"),
    updatemenus = list(
      list(
        y = 0.7,
        buttons = list(
          list(method = "restyle",
               args = list("color", list(~z)),  
               label = "group by z"),
          list(method = "restyle",
               args = list("color", list(~w)),  
               label = "group by w")))
    ))

enter image description here

However, switching between the two options, the plot does not change. Apparently, we could change any data attribute with dropdown events except the color! Any help would be appreciated.

Upvotes: 3

Views: 1121

Answers (1)

Dave Gruenewald
Dave Gruenewald

Reputation: 5689

Unfortunately I don't believe this is possible with solely using plotly:

Per a github issue:

color/symbol/linetype/size/etc mapping (from data values to color codes) happen on the R side of things, so once the plot object gets passed to the browser, it loses information about those mapping(s), so I'm afraid something like this won't be possible...unless you do the mapping yourself

Alternatives

This seems to be a nice use case for shiny. There is a stack overflow question that shows you these steps on creating a menu outside of plotly, and using the selection to re-render the plot.

Additionally, you can change the color of the plot by using plotly.js and HTML. You would have to add select elements to a HTML page, and add event listeners to call Plotly.newPlot() on update. I believe shiny is an easier solution as it's a bit more of an R-centric approach.

Upvotes: 1

Related Questions