Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically add layers to plotly in R

Tags:

r

plotly

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?

like image 820
OldMcFartigan Avatar asked Apr 28 '26 21:04

OldMcFartigan


1 Answers

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.

like image 82
OldMcFartigan Avatar answered May 01 '26 12:05

OldMcFartigan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!