简体   繁体   中英

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

在此处输入图像描述

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM