Search code examples
rplotlyr-plotly

Why is only the last added trace displayed when adding traces iteratively to a Plotly object using R?


library(plotly)

V <- data.frame(t, A, B, C, D, E, F)

pic <- plot_ly(V, x = ~t) %>% 
         add_trace(y = ~40000*exp(-t/7), name = "P(t)",
                   type = "scatter", mode="lines",
                   line=list(color="gray",width=2)
                  ) %>%
        layout(yaxis=list(title="Amount / million euros",zeroline=TRUE),
               xaxis = list(title="t",zeroline = TRUE)
              )

CLR <- c("darkblue", "powderblue", "mediumaquamarine", "darkred", "wheat", "tan")
for (j in 1:6)
{
  pic <- pic %>%
    add_trace(y = ~V[,j+1], name = colnames(V)[j+1],
              type = "scatter", mode = 'lines+markers',
              marker=list(size=8,color=CLR[j]),
              line=list(color=CLR[j],width=1.5)
             )
  print(pic)
}

I have a dataframe of 7 columns, V, and I want to plot the last 6 columns against the first one by adding one trace each time to the plotly object pic. Yet when I print out pic at the end of each iteration, only the last added trace is displayed and all the previous traces are gone. Legends are all there, though. Why does this happen? How can I fix it?


Solution

  • Two possible solutions.

    set.seed(123)
    t <- 1:20
    A <- 4*exp(-t/7)+rnorm(20)*0.1
    B <- 4*exp(-t/7)+rnorm(20)*0.2
    C <- 4*exp(-t/7)+rnorm(20)*0.3
    D <- 4*exp(-t/7)+rnorm(20)*0.4
    E <- 4*exp(-t/7)+rnorm(20)*0.5
    F <- 4*exp(-t/7)+rnorm(20)*0.6
    V <- data.frame(t, A, B, C, D, E, F)
    
    pic <- plot_ly(data=V, x = ~t) %>% 
             add_trace(y = ~4*exp(-t/7), name = "P(t)",
                       type = "scatter", mode="lines",
                       line=list(color="gray",width=2)
                      ) %>%
            layout(yaxis=list(title="Amount / million euros",zeroline=TRUE),
                   xaxis = list(title="t",zeroline = TRUE)
                  )
    
    CLR <- c("darkblue", "powderblue", "mediumaquamarine", "darkred", "wheat", "tan")
    for (j in 1:6) {
      pic <- pic %>%
        add_trace(x = V[,1], y = V[,j+1], name = colnames(V)[j+1],
                  type = "scatter", mode = 'lines+markers',
                  marker=list(size=8, color=CLR[j]),
                  line=list(color=CLR[j], width=1.5, inherit.aes=F)
                 )
    }
    print(pic)
    

    Or

    for (j in 1:6) {
      df <- data.frame(x=V[,1], y=V[,j+1])
      pic <- pic %>%
        add_trace(data=df, x = ~x, y = ~y, name = colnames(V)[j+1],
                  type = "scatter", mode = 'lines+markers',
                  marker=list(size=8, color=CLR[j]),
                  line=list(color=CLR[j], width=1.5)
                 )
    }
    

    enter image description here