3

I'm trying to plot a surface plot of a function by generating the points myself via a for loop. The graph however doesn't show up. I've read that the z entry in the data variable for surface plots has to be an array of arrays but even that hasn't made the plot show up.

var zPts = [];
var xPts = [];
var yPts = [];

for(x=0; x<1; x+=0.01) {
  for (y=0; y<1; y+=0.01) {
  zPts.push([Math.sin(x*y)]);
  yPts.push(y);
  xPts.push(x);
  }
  }

var data = [{
    z: zPts,
    x: xPts,
    y: yPts,
    type: 'surface'
  }];
  
  var layout = {
    title: 'My Plot',
    autosize: false,  
    width: 500,
    height: 500,
    margin: {
      l: 65,
      r: 50,
      b: 65,
      t: 90,
    }
  };
  
  Plotly.newPlot('theDiv', data, layout);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="theDiv"></div>

1 Answer 1

1

After some messing around I've found that the following code produces the plots needed with only the addition of 3 temporary array variables needed. I believe the correct formatting for the data is that the x, y and z arrays have to all be an array of arrays with each sub array being the same size for all 3.

var zPts = []; 
var xPts = [];
var yPts = [];


for(x=0; x<10; x+=0.1) {
  let zTemp = [];
  let yTemp = [];
  let xTemp = [];
  for (y=0; y<10; y+=0.1) {
    zTemp.push(Math.sin(x)*Math.cos(y));
    yTemp.push(y);
    xTemp.push(x);
  }
  zPts.push(zTemp);
  yPts.push(yTemp);
  xPts.push(xTemp);
  }

var data = [{
    z: zPts,
    x: xPts,
    y: yPts,
    type: 'surface'
  }];
  
  var layout = {
    title: 'My Plot',
    autosize: false,  
    width: 500,
    height: 500,
    margin: {
      l: 65,
      r: 50,
      b: 65,
      t: 90,
    }
  };
  
  Plotly.newPlot('theDiv', data, layout);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="theDiv"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.