Optimizing add_trace() in a for loop?
<p>I'm using the <strong>add_trace()</strong> function in a <strong>for</strong> loop to create lines for a 3d network graph in plotly's scatter3d mode. Each add_trace draws an individual line between two nodes in the network. The method is working, but with large number of loops, the speed of the individual loops seems to be slowing down very quickly.</p>

<p>Example data can be downloaded here: <a href="https://gist.github.com/pravj/9168fe52823c1702a07b" rel="nofollow">https://gist.github.com/pravj/9168fe52823c1702a07b</a></p>

<pre><code>library(igraph)
library(plotly)

G &lt;- read.graph("karate.gml", format = c("gml"))
L &lt;- layout.circle(G)

vs &lt;- V(G)
es &lt;- as.data.frame(get.edgelist(G))

Nv &lt;- length(vs)
Ne &lt;- length(es[1]$V1)

Xn &lt;- L[,1]
Yn &lt;- L[,2]

network &lt;- plot_ly(type = "scatter3d", x = Xn, y = Yn, z = rep(0, Ne), mode = "markers", text = vs$label, hoverinfo = "text", showlegend = F)

for(i in 1:Ne) {
  v0 &lt;- es[i,]$V1
  v1 &lt;- es[i,]$V2

  x0 &lt;-  Xn[v0]
  y0 &lt;-  Yn[v0]
  x1 &lt;-  Xn[v1]
  y1 &lt;-  Yn[v1]

  df &lt;-  data.frame(x = c(x0, x1), y = c(y0, y1), z = c(0, 0))
  network &lt;- add_trace(network, data = df, x = x, y = y, z = z, type = "scatter3d", mode = "lines", showlegend = F, 
                       marker = list(color = '#030303'), line = list(width = 0.5))
}
</code></pre>

<p>This example is fairly quick, but when I include a few hundred edges or more, the execution of the individual loops start to slow down radically. I tried different optimization methods (vectorisation etc), but there seems to be no working around the slowness of the add_trace function itself.</p>

<p>Any suggestions?   </p>