Selecting/Deselecting traces from code

Hi everyone!
A question about plotly -

I wonder if there’s any way to select or deselect traces from inside the code just the way we tend to do with clicking on the legends?

I don’t want to subset the data, I just want to control the visibility of the plot.

which plotting functionality are you using ggplot2? plotly? something else ?

alternatively, if you can share a minimal reproducable example of such a plot that you want to do this to, someone here with familiarity might be able to amend it for you.

Sorry for that! I was stuck in my head and I didn't notice that I haven't mentioned that I'm using plotly! I edited the original question, I can't do a reprex() for a plot but I think that this code will work well:

library(plotly)
set.seed(42)
data.frame(cat = rep(c("A","B","C"),10),
x = rnorm(30),
y = rnorm(30)) %>%
plot_ly(x=~x, y=~y, color =~cat) %>%
add_lines()

one way to do it dynamically would be via javascript, or else perhaps it would be something like exporting the plotly object to a json format, editting it to make some trace legendonly visibility and somehow buildoing the plotly object back and rerendering it. I gave that ago but the obvious didnt work. maybe I should post a question :laughing:

Here is how you can build it with visibility of 'B' altered.

library(plotly)
library(tidyverse)
library(listviewer)
library(jsonlite)
set.seed(42)
df1 <- data.frame(cat = rep(c("A","B","C"),10),
           x = rnorm(30),
           y = rnorm(30)) %>% arrange(x)

p <-   plot_ly(width=400,
               height=400,
               df1,
               x=~x,
               y=~y,
               color =~cat) %>% add_lines()


df2 <- pivot_wider(df1,
                   names_from = cat,
                   values_from = y,
                   names_prefix = "y_"
                   ) %>% arrange(x)

p2 <-   plot_ly(width=400,
                height=400,
                df2,
                x=~x) %>%
  add_trace(y=~y_A, name="A",mode="lines", connectgaps = TRUE) %>%
  add_trace(y=~y_B, name="B",mode="lines", connectgaps = TRUE,visible="legendonly") %>%
  add_trace(y=~y_C, name="C",mode="lines", connectgaps = TRUE)

Rplot1
Rplot2

1 Like

Thanks a lot! It was really useful! :grinning:
Just instead of adding a new trace, you can restyle the existing ones:

library(plotly)
set.seed(42)
data.frame(cat = rep(c("A","B","C"),10),
x = rnorm(30),
y = rnorm(30)) %>%
plot_ly(x=~x, y=~y, color =~cat) %>%
add_lines() %>%
style(visible = "legendonly", traces = c(1,3))

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.