[英]Plotly: add_trace in a loop
我正在嘗試在每個循環中添加ad_trace廣告,但我只得到一個圖表,其中彼此相乘。
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)
plot_ly
和add_trace
函數有一個add_trace
evaluation = FALSE
選項,您可以將其更改為TRUE
,這應該可以解決范圍問題。
在add_trace
使用evaluate = TRUE
。
討厭,但有效:
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)
我這樣做是這樣的:
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()
)
它在這里描述: http : //www.r-graph-gallery.com/129-use-a-loop-to-add-trace-with-plotly/
將您的繪圖保存在變量中,然后執行add_trace:
p <- plotly(...)
p<- add_trace(p, ...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.