0

I tried to use a function with a loop for not having to add manually every trace. But it does not work.

library(tidyverse)
library(plotly)

df <- tibble(year = c("2019", "2020"),
             x = c(1, 2),
             y = c(3, 5),
             z = c(2, 7))


addmore <- function(fig, i){
  fig %>% add_trace(y = ~df[[i]], name = colnames(df[i]),
                    mode = 'lines+markers',
                    line = list(width = 1)) -> fig
}

# This does not work

fig <- plot_ly(df, x = ~year, y = ~df[[2]],
               name = colnames(df[2]), type = 'scatter',
               mode = 'lines+markers',
               line = list(width = 1)) 

for (i in 3:4){
  addmore(fig, i)
}

fig <- fig %>% layout(title = "Sample",
                      xaxis = list(title = "Years"),
                      yaxis = list (title = "Values"))

fig
2
  • You should include dom_w in your code so we can run it (use the dput function) Commented Oct 29, 2020 at 11:53
  • It was an error. It is corrected now. Commented Oct 29, 2020 at 11:56

1 Answer 1

1
for (i in 3:4){
 fig <- addmore(fig, i)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.