How to create 3D plots of surfaces on WordPress

Instead of creating 3D plots of surfaces using Matlab and then converting the result into an image, I would like to show you how to create a 3D plot of an equation or a function directly from your WordPress.

First, we need to install CSS & Javascript Toolbox (CJT). CJT is a wordpress plugin that enable us to add custom css and javascript code into specific posts, categories, or pages. We know that not all posts will contain the graphics. After that, make a new block code and insert this code to the field.

<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.18.1/vis.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.18.1/vis.min.css" rel="stylesheet" type="text/css" />

Yes, as you notice, there are only two lines of code involved. The first line is used to add additional javascript code to our post and the second one is used to add styling to our post. In order to display 3D graphics, we need a library that can help us doing this task, it’s Vis.js. Vis.js is a dynamic, browser based visualization library. The library is designed to be easy to use, to handle large amounts of dynamic data, and to enable manipulation of and interaction with the data. The library consists of the components DataSet, Timeline, Network, Graph2d and Graph3d.

And the last part is inserting our code to create 3D graphics using Vis.js. I’m gonna use an example from Vis.js website, the graphic has equation of $sin(\frac{x}{50})cos(\frac{y}{50})50 + 50)$. Simply, put this code to your post to render the graphic.

Visit this link to see the result.

<div id="visualization"></div>
<script type="text/javascript">
  // Create and populate a data table.
  var data = new vis.DataSet();
  // create some nice looking data with sin/cos
  var counter = 0;
  var steps = 50; // number of datapoints will be steps*steps
  var axisMax = 314;
  var axisStep = axisMax / steps;
  for (var x = 0; x < axisMax; x+=axisStep) {
   for (var y = 0; y < axisMax; y+=axisStep) {
     var value = (Math.sin(x/50) * Math.cos(y/50) * 50 + 50);
     data.add({id:counter++,x:x,y:y,z:value,style:value});
   }
  }

  // specify options
  var options = {
    width: '400px',
    height: '452px',
    style: 'surface',
   showPerspective: true,
   showGrid: true,
   showShadow: false,
   keepAspectRatio: true,
   verticalRatio: 0.5
  };

  // Instantiate our graph object.
  var container = document.getElementById('visualization');
  var graph3d = new vis.Graph3d(container, data, options);
</script>