I would like to pass new traces to plotly::add_lines
in a programmatic way, so that buttons appear for each new trace. For example, say my data frame is this:
df <- data.frame(var = rep(c("A","B","C","D"), each = 20),
value = rnorm(80),
time = rep(c(1:20),4)) %>%
tidyr::spread(var, value)
To get buttons on my plotly figure, I would use updatemenus
within the plotly::layout
function as follows:
updatemenus <- list(
list(
active = -1,
type= 'buttons',
direction = "right",
xanchor = 'center',
yanchor = "top",
pad = list('r'= 0, 't'= -25, 'b' = 0),
buttons = list(
list(
label = "A",
method = "update",
args = list(list(visible = c(T, F, F, F)),
list(title = "A"))),
list(
label = "B",
method = "update",
args = list(list(visible = c(F, T, F, F)),
list(title = "B"))),
list(
label = "C",
method = "update",
args = list(list(visible = c(F, F, T, F)),
list(title = "C"))),
list(
label = "D",
method = "update",
args = list(list(visible = c(F, F, F, T)),
list(title = "D"))),
list(
label = "All",
method = "update",
args = list(list(visible = c(T, T, T, T)),
list(title = "All")))
)
)
)
Then, to display the figure with buttons for adding and subtracting lines:
df %>%
plot_ly(type = 'scatter', mode = 'lines') %>%
add_lines(x=~time, y=~A, name="Data") %>%
add_lines(x=~time, y=~B, name="Data") %>%
add_lines(x=~time, y=~C, name="Data") %>%
add_lines(x=~time, y=~D, name="Data") %>%
layout(updatemenus=updatemenus)
What I would like to do is write a function that adds columns in a data.frame to the updatemenus
list while also adding them to the plotly
figure through new add_lines
additions. Has anyone attempted this before? Is it possible to pass a list with this information to piped plotly functions?
Sean