keiv.fly
keiv.fly

Reputation: 4085

Creating Plotly in R in loops shows the last chart for all elements

I am trying to create a subplot with several plotly charts but when I create the charts in a for loop and then use subplot() all the charts are reassigned to the last one. I suppose it is something to do with how plotly creates charts. It first creates only the parameters and then executes. But I want different charts. Can someone help me?

Here is the code to reproduce the problem:

library(plotly)
df=data.frame(x=1:10,y1=1:10,y2=11:20)
cols=c("y1","y2")
vec_of_plots=list()
for (i_col in seq_along(cols)){
  dat=df[,c("x",cols[i_col])]
  vec_of_plots[[i_col]]=plot_ly(x = dat[,1], y = dat[,2])
}
subplot(vec_of_plots)

Here is the result:

enter image description here

But the first chart should be from 1 to 10 and not from 11 to 20.

I looked through other questions on Stackoverflow and could not find the answer. Here I use no qqplot and no ggplot, just pure plotly.

Upvotes: 1

Views: 361

Answers (1)

Abdou
Abdou

Reputation: 13274

While I cannot figure out why calling the subplot function directly on a list does not yield the right result, I am proposing that you try the following solution:

library(plotly)
mydf <- data.frame(x=1:10,y1=1:10,y2=11:20)

do.call(subplot, lapply(colnames(mydf)[2:3], function(column_name) {
    plot_ly(x = mydf$x, y = mydf[,column_name])
}))

enter image description here

I hope this helps.

Upvotes: 1

Related Questions