简体   繁体   中英

Programmatically add layers to plotly in R

I am trying to add layers in plotly programmatically but can't seem to get around it's lazy evaluation. Example:

p <- plot_ly()

for(kk in 1:5) {
  tmp <- cbind(rnorm(1) + 0.05*rnorm(15),rnorm(1) + 0.05*rnorm(15))
  p %<>% add_trace(x = tmp[,1], y = tmp[,2], type = "scatter", mode = "markers")  
}

In this example I was trying to plot a gaussian mixture model, however, the arguments to plotly aren't evaluated until they are viewed, so all five layers contain only the final value of tmp. The command plotly_build is supposed force evaluation but I can't find examples of its usage and apparently I'm doing it wrong.

p <- plot_ly()

for(kk in 1:5) {
  tmp <- cbind(rnorm(1) + 0.05*rnorm(15),rnorm(1) + 0.05*rnorm(15))
  p %<>% add_trace(x = tmp[,1], y = tmp[,2], type = "scatter", mode = "markers")
  plotly_build(p)     
}

Still gives the same result. What am I doing wrong?

p <- plot_ly()

for(kk in 1:5) {
  tmp <- cbind(rnorm(1) + 0.05*rnorm(15),rnorm(1) + 0.05*rnorm(15))
  p %<>% add_trace(x = tmp[,1], y = tmp[,2], type = "scatter", mode = "markers", evaluate = TRUE)  
}

There is an evaluate argument to plotly.

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