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
Here is how you can build it with visibility of 'B' altered.