Search code examples
rfor-loopplotplotly

Create a Plotly plot of all the columns in a dataframe in a loop


I want to use a loop to plot each of the columns as individual lines in a dataframe into a Plot_ly scatter plot. The loop is plotting each of the columns as the same value from the last column. Here is a simplified example:

library(plotly)

# Creating a sequence of dates
dates <- seq(as.Date("2023-01-01"), by = "day", length.out = 5)  
# Creating the dataframe with 5 rows and 5 columns
t_df <- data.frame(
  Date = dates,
  Column2 = c(1, 2, 3, 4, 5),
  Column3 = c(6, 7, 8, 9, 10),
  Column4 = c(11, 12, 13, 14, 15),
  Column5 = c(16, 17, 18, 19, 20)
)
#Initializing the plot
plot <- plot_ly(data = t_df)
#loop to add each trace to the plot
for (i in 2:ncol(t_df)){
  i = 3
  plot <- add_trace(plot, data = t_df, x = ~Date, y = ~t_df[,i], type = 'scatter', mode = 'lines', name = names(t_df)[i])
}
print(plot)

This is what the current script produces: enter image description here

Any thoughts?


Solution

  • I think the issue is due to two typos, remove ~ from y = ~t_df[,i] and, of course, i = 3:

    for (i in 2:ncol(t_df)) { 
      plot <- add_trace(plot, data = t_df, x = ~Date, y = t_df[, i], 
                        type = 'scatter', mode = 'lines', name = names(t_df)[i])
    }