Merge traces in one figure

I’m new to plotly in R, i’ve always used it in Python. I’m trying to create a function that returns a trace each time I call that function. I can give you a minimal working example

fig <- plot_ly()
plotfunc <- function(k) {
    x <- 0:10
    y <- k*x
    fig <- add_trace(fig, x=x, y=y, type='scatter')
    return(fig)
}
plotfunc(1)
plotfunc(2)
plotfunc(3)

I’d like to view all these traces in one plot. The figure should also only be shown on the last call of the function.
Do you know if it is possible in some way?

Also i know i could just change the structure so that the function is taking a set of k values and then loop over those values. Like this

plotfunc <- function(kvec) {
    fig <- plot_ly()
    for (k in kvec) {
    x <- 0:10
    y <- k*x
    fig <- add_trace(fig, x=x, y=y, type='scatter')
    }
    return(fig)
}
plotfunc(c(1,2,3))

But I’m wondering if there is a simple way to merge different figures since I find it more flexible then looping over a vector.

I’d recommend using plot_ly’s built-in split parameter (or color or name - see ?plot_ly) to create multiple traces based on a long format data.frame:

DF <- data.frame(id = rep(LETTERS[1:3], each = 10), x_val = rep(1:10, 3), y_val = runif(30L))
plot_ly(data = DF, x = ~x_val, y = ~y_val, split = ~id, type = "scatter", mode = "lines+markers")