简体   繁体   中英

Plotly add_trace using lapply or for loops doesnt work

How can I add_trace in a loop when using a list of dataframes

I keep getting the following using code below

df1<-c(seq(1:32))
df2<-df*2
df3<-df2*8
dff1<-sqrt(df1)
dff2<-sqrt(df2)
dff3<-sqrt(df3)


a<-cbind.data.frame(df1,dff1)
b<-cbind.data.frame(df2,dff2)
c<-cbind.data.frame(df3,dff3)
colnames(a)<-c("df1","df2")
colnames(b)<-c("df1","df2")
colnames(c)<-c("df1","df2")

df<-list()
df[[1]]<-a
df[[2]]<-b
df[[3]]<-c

pl<-plot_ly()
for(i in 1:3){

  pl<- add_trace(pl,data=df[[i]],x=~df[[i]]$df1,y=~df[[i]]$df2,mode='lines',type='scatter') 


}

pl

在此处输入图片说明

and when using lapply instead of for loops i get three seperate graphs instead of one graph with three lines

pl<-plot_ly()

pl<-lapply(1:3, function(i){

  pl<- pl%>%
    add_trace(data=df[[i]],x=~df[[i]]$df1,y=~df[[i]]$df2,mode='lines',type='scatter',inherit = TRUE) 


})
pl

While other users have correctly noted that this can simply be done with a for loop, I figured I might as well just answer how to do it with lapply() for any future folks who come upon this question.

This can be done with lapply() by using the get() method, which allows you to specify the environment when retrieving a variable. Wrapping your lapply with invisible() prevents the loop from printing intermediates to you console/viewer as it runs.

Here is the code:

df1<-c(seq(1:32))
df2<-df1*2
df3<-df2*8
dff1<-sqrt(df1)
dff2<-sqrt(df2)
dff3<-sqrt(df3)


a<-cbind.data.frame(df1,dff1)
b<-cbind.data.frame(df2,dff2)
c<-cbind.data.frame(df3,dff3)
colnames(a)<-c("df1","df2")
colnames(b)<-c("df1","df2")
colnames(c)<-c("df1","df2")

df<-list()
df[[1]]<-a
df[[2]]<-b
df[[3]]<-c

pl<-plot_ly()

invisible(lapply(seq_along(df), FUN = function(i) {
  pl <<- get("pl", envir = globalenv()) %>% 
    add_trace(pl,data=df[[i]],x=~df[[i]]$df1,y=~df[[i]]$df2,mode='lines',type='scatter')  
}))

pl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM