Plotly rotation animation and changing camera eye in R

211 views Asked by At

I am having trouble changing the camera eye in my rotating animation of a plotly "scatter3d" plot.

I can specify the camera eye using the layout function in the plotly R package.

fig %>% 
  layout(
    scene = list(
      aspectratio = list(x = 1, y = 1, z = -1),
      camera = list(
        center = list(x = 0, y = 0, z = 0),
        eye = list(x = -.1, y = .5, z = 1.5)),
      up = list(x = 0, y = 0, z = 0),
      xaxis = list(showgrid = FALSE, zeroline = FALSE, range = c(-10, 10),
                   showticklabels = FALSE, title = list(text = "")),
      yaxis = list(showgrid = FALSE, zeroline = FALSE, range = c(-10, 10),
                   showticklabels = FALSE, title = list(text = "")),
      zaxis = list(showgrid = FALSE, zeroline = FALSE, range = c(-10, 10),
                   showticklabels = FALSE, title = list(text = "")),
      dragmode = "turntable",
      aspectmode='cube'#,
      #annotations = annots
    ), margin = list(t = 30, r = 30, l = 30, b = 30, padding = 2))%>%

Where fig is a "plotly" "htmlwidget" of type "scatter3d"

yielding the following plot: plot with correct camera eye

I added the following code with the htmlwidget package to create a rotating animation but the camera eye gets reset.

%>%
  
  onRender(
    '
  function(el, x) {
    var id = el.getAttribute("id");
    var gd = document.getElementById(id);
    Plotly.update(id).then(attach);
    
    function attach() {
      var cnt = 0;
      
      function run() {
        rotate("scene", Math.PI / 360);
        requestAnimationFrame(run);
      } 
      run();
      
      function rotate(id, angle) {
        var eye0 = gd.layout[id].camera.eye;
        var rtz = xyz2rtz(eye0);
        rtz.t += angle;
        
        var eye1 = rtz2xyz(rtz);
        Plotly.relayout(gd, id + ".camera.eye", eye1)
      }
      
      function xyz2rtz(xyz) {
        return {
          r: Math.sqrt(xyz.x * xyz.x + xyz.y * xyz.y),
          t: Math.atan2(xyz.y, xyz.x),
          z: xyz.z
        };
      }
      
      function rtz2xyz(rtz) {
        return {
          x: rtz.r * Math.cos(rtz.t),
          y: rtz.r * Math.sin(rtz.t),
          z: rtz.z
        };
      }
    }
  }
  '
  )  

Yeilding the following animation: rotating plot with unfavorable camera eye

I would really like for the rotation to be from the first camera eye and spin. Can anybody help with this?

0

There are 0 answers