使用lapply或for循环来密谋add_trace不起作用 [英] Plotly add_trace using lapply or for loops doesnt work
问题描述
使用数据帧列表时如何在循环中添加_trace
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
当使用lapply代替for循环时,我得到了三个单独的图形,而不是一个带有三行的图形
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
推荐答案
虽然其他用户正确地指出,可以使用for循环轻松完成此操作,但我想我也可以通过lapply()来回答问题对于以后遇到这个问题的任何人.
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.
这可以通过使用get()方法使用lapply()完成,该方法允许您在检索变量时指定环境.用invisible()包装您的lapply可以防止循环在运行时将中间内容打印到控制台/查看器.
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.
这是代码:
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
这篇关于使用lapply或for循环来密谋add_trace不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!