R Plotly:在循环中添加_跟踪
我试图在每个循环中添加跟踪,但我只得到一个曲线图,每个曲线图上都有相乘的直线R Plotly:在循环中添加_跟踪,r,plot,ggplot2,plotly,R,Plot,Ggplot2,Plotly,我试图在每个循环中添加跟踪,但我只得到一个曲线图,每个曲线图上都有相乘的直线 mean <- -0.0007200342 sd <- 0.3403711 N=10 T=1 Delta = T/N W = c(0,cumsum( sqrt(Delta) * rnorm(N, mean=mean, sd=sd))) t <- seq(0,T, length=N+1) p<-plot_ly(y=W, x=t) for(i in 1:5){ W <- c(0
mean <- -0.0007200342
sd <- 0.3403711
N=10
T=1
Delta = T/N
W = c(0,cumsum( sqrt(Delta) * rnorm(N, mean=mean, sd=sd)))
t <- seq(0,T, length=N+1)
p<-plot_ly(y=W, x=t)
for(i in 1:5){
W <- c(0,cumsum( sqrt(Delta) * rnorm(N, mean=mean, sd=sd)))
p<-add_trace(p, y=W)
}
print(p)
mean讨厌,但有效:
mean <- -0.0007200342
sd <- 0.3403711
N=10
T=1
Delta = T/N
W = c(0,cumsum( sqrt(Delta) * rnorm(N, mean=mean, sd=sd)))
t <- seq(0,T, length=N+1)
for(i in 1:5){
W <- c(0,cumsum( sqrt(Delta) * rnorm(N, mean=mean, sd=sd)))
assign(paste("W_",i,sep=""),W)
assign(paste("Name_", i, sep=""), paste("Name",i,sep=""))
if(i==1){
pString<-"p<-plot_ly(x = t, y = W_1, name='W1')"
} else {
pString<-paste(pString, " %>% add_trace(x=t, y =", eval(paste("W", i, sep="_")),", name=", eval(paste("Name", i, sep="_")), ")", sep="")
}
}
eval(parse(text=pString))
print(p)
meanplot\u ly
和add\u trace
函数有一个evaluation=FALSE
选项,您可以将其更改为TRUE
,这将解决范围问题。在add\u trace中使用evaluate=TRUE
,我会这样做:
mean <- -0.0007200342
sd <- 0.3403711
N=10
T=1
Delta = T/N
# a list with the trace Y values
Ws <- lapply(
1:15,
function(idx){
c(0,cumsum( sqrt(Delta) * rnorm(N, mean=mean, sd=sd)))
}
)
# this could be a list with the trace X values, but is just a seq
t <- seq(0,T, length=N+1)
# a list with plotly compliant formatted objects
formattedW <- lapply(
seq_along(Ws),
function(idx, datasetY, datasetX){
return(list( x = datasetX, y = datasetY[[idx]], type="scatter", mode = 'lines+markers'))
},
datasetX = t,
datasetY = Ws
)
# Reduce the list of plotly compliant objs, starting with the plot_ly() value and adding the `add_trace` at the following iterations
Reduce(
function(acc, curr){
do.call(add_trace,c(list(p=acc),curr))
},
formattedW,
init=plot_ly()
)
mean如下所述:
将绘图保存在变量中,然后添加跟踪:
p <- plotly(...)
p<- add_trace(p, ...)
p我想这是一个范围问题。定义y=W
时,首先在绘图环境中找到W
。直接使用pAlso对这里的解决方案感兴趣..似乎是一个普遍的问题?我的意思是,前面提到的解决方案适用于这个简单的示例,但如果您有大数据帧,则不适用。一旦plotly调用中有soom循环变量或任何内容,它只接受最后一个循环变量。。。