I have a plot with multiple lines and would like to initialize it with just some layers active. Is it possible? Here is an example of what the data looks like:
set.seed(101)
df <- data.frame(x = seq(1,20,1),
y1 = runif(20),
y2 = runif(20),
y3 = runif(20),
y4 = runif(20))
plot_ly(df, x = ~x) %>%
add_lines(y = ~y1, name='y1', line = list(color = 'rgba(255,0,0,1')) %>%
add_lines(y = ~y2, name='y2', line = list(color = 'rgba(0,255,0,1')) %>%
add_lines(y = ~y3, name='y3', line = list(color = 'rgba(106,90,205,1')) %>%
add_lines(y = ~y4, name='y4', line = list(color = 'rgba(0,0,255,1')) %>%
layout(
xaxis = list(title = "x", domain = c(0,1), tickmode = 'auto'),
yaxis = list(title = 'y', side = "left", color = "black", position = 0,
anchor = 'free', range = c(0,1), dtick = 1),
showlegend = T
)
What I want is to generate a plot with all lines, but e.g. with y3 and y4 off and still allow the user to turn it on (this plot is part of a shiny app).
Is it even possible?
Thanks!
You need to set visible = "legendonly"
for the traces you want to hide:
library(plotly)
set.seed(101)
df <- data.frame(x = seq(1,20,1),
y1 = runif(20),
y2 = runif(20),
y3 = runif(20),
y4 = runif(20))
plot_ly(df, x = ~x) %>%
add_lines(y = ~y1, name='y1', line = list(color = 'rgba(255,0,0,1')) %>%
add_lines(y = ~y2, name='y2', line = list(color = 'rgba(0,255,0,1')) %>%
add_lines(y = ~y3, name='y3', line = list(color = 'rgba(106,90,205,1'), visible = "legendonly") %>%
add_lines(y = ~y4, name='y4', line = list(color = 'rgba(0,0,255,1'), visible = "legendonly") %>%
layout(
xaxis = list(title = "x", domain = c(0,1), tickmode = 'auto'),
yaxis = list(title = 'y', side = "left", color = "black", position = 0,
anchor = 'free', range = c(0,1), dtick = 1),
showlegend = TRUE
)
To get more information regarding the available trace attributes use:
schema()
and navigate as follows:
object ► traces ► scatter ► attributes