DEV Community

Cover image for How to Create a 3D Surface Chart in JavaScript
andreykh
andreykh

Posted on • Updated on • Originally published at anychart.com

How to Create a 3D Surface Chart in JavaScript

🌈 Creating an embeddable interactive 3D Surface Plot is not as tricky as it may seem. A new tutorial on Hongkiat demonstrates a way that must be easy even for beginners! 🔥

🙋 Learn how to build a compelling surface chart using JavaScript in four quick steps and then customize it to your liking in just a few more lines of code. For an illustrative example, 15 years of GDP data for 195 countries are being visualized along the article — have fun exploring the final diagram, too!

Data visualization is a must-have skill today with ever-growing data and the need to analyze as well as present that data. You will definitely come across data charts whether you are in the technology industry or not and therefore, it is a good idea to learn how to build visualizations.

I will show you here that building charts is not very tough and with the right tools, you can start creating interactive, interesting visualizations in little time and effort!

In this step-by-step tutorial, I will demonstrate how to represent GDP values of various countries for the past 15 years on a beautiful interactive 3D surface chart using a JavaScript library for data visualization.

The surface plot looks quite complex, but I will show you how straightforward it is to make a compelling and fully functional one.

What’s a 3D Surface Chart?

A 3D surface chart plots three dimensions of data on the x, y, and z axes with two of the variables being independent (displayed along the horizontal axes) and one being dependent on the other two (shown on the vertical axis).

In this tutorial, I will be plotting countries and years as the independent variables and GDP values as the dependent variable.

JavaScript Charting Libraries

Currently, there are a lot of good JS charting libraries, all of them having some pros and cons. You can choose which one to use based on your specific requirements and the best part is that the process of building visualizations is very similar for all of the libraries. So, you can start learning with any of the libraries and extend your knowledge to another library as well.

For this tutorial, I am going to use the AnyChart JavaScript charting library which is likely a good choice for beginners. It has tons of examples along with extensive documentation that is really useful when starting out.

Also, AnyChart is quite easy to use and flexible with loads of customization options. And what’s especially important to many — it is free for personal, educational, and other non-commercial use.

Building Basic 3D Surface Plot Using a JS Library

It is an advantage, of course, if you have background knowledge of HTML, CSS, and JavaScript. But don’t get overwhelmed even if you are a complete beginner. I will walk you through each line of the code, and once you understand what is happening, it should get easier to grasp.

There are four general steps to create a 3D surface plot or basically any chart with a JS library, and as mentioned earlier, these steps remain alike irrespective of the library you use.

  • Create an HTML page to display your chart.
  • Include the required JavaScript files.
  • Prepare and connect your data.
  • Write the JS code for the chart.

Step 1 — Create a basic HTML page

The initial step is to have a blank HTML page that will hold the chart. I will add a block element with a unique id to the page. I will use the id to reference the <div> later.

I will now specify the height and width of the <div> as 100% for both in the <style> block of the page. This will render the chart on the full page. You can specify the height and width according to your preference.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Surface Chart</title>
    <style type="text/css">   
      html, body, #container {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 2 — Add the necessary scripts

When you are using a JavaScript library, you need to add the scripts specific to the chart that you are building and the library that you are using.

Here, I am using AnyChart so I need to add the corresponding scripts for the surface plot from its CDN (Content Delivery Network) which is basically where all the scripts can be found.

So, I will include AnyChart’s Core and Surface modules for this chart.

Just to remind you, include all these script files in the <head> section of your HTML page.

<!DOCTYPE html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <title>JavaScript Surface Chart</title>
  <script src="https://cdn.anychart.com/releases/8.10.0/js/anychart-core.min.js"></script>
  <script src="https://cdn.anychart.com/releases/8.10.0/js/anychart-surface.min.js"></script>
  <script src="https://cdn.anychart.com/releases/8.10.0/js/anychart-data-adapter.min.js"></script>
  <style type="text/css">   
    html, body, #container {
      width: 100%; height: 100%; margin: 0; padding: 0;
    }
  </style>
  </head>
  <body> 
    <div id="container"></div>
    <script>
      // All the code for the JS Surface Chart will come here
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 3 — Include the data

The data I decided to visualize in a 3D surface plot comes from the World Bank Open Data website that gives me the GDP (PPP based) data for all the countries in a CSV file.

It is easier to create a chart if the data is in the format that the chart expects and how you want to show the data. So I pre-processed the data accordingly. You can go through my JSON data file here.

To load the data from the JSON file, I will add the Data Adapter module of AnyChart and use the loadJsonFile method inside the <script> tag in the body of the HTML page.

The three preparatory steps are done so get ready to write some code!

Step 4 — Write the code to draw the chart

The first thing I will do is ensure that all the code is executed only after the page is fully loaded. To do that, I will enclose the entire code within the anychart.onDocumentReady() function.

Then, I will work with the data that is loaded from the JSON file. Even though I have already pre-processed the data, I will need to further process it for plotting the 3D surface chart. Basically, I will create an array that holds the y and z axes data according to the sequence of the x axis data.

anychart.onDocumentReady(function () {
  anychart.data.loadJsonFile(
    'https://gist.githubusercontent.com/shacheeswadia/b0d6b34a1910359e0e1a8fc0c84019a6/raw/4ab92ca6361f1bc9875d2854e2e1271bc991f86b/surfaceAreaData.json',
    function (data) {
      // processing of the data
      var result = [];
      for (var x = 0; x < data.x.length; x++) {
        for (var y = 0; y < data.y.length; y++) {
          result.push([x, data.y.sort()[y], data.z[x][y]]);
        }
      }
    }
  );
});
Enter fullscreen mode Exit fullscreen mode

Now, I will create the surface chart and set the markers based on the data array just created.

Next, I will need to set the x axis labels from the loaded data because the array that I created contains only a sequence and not the country names. I will also specify the maximum for the x scale.

// create surface chart
var chart = anychart.surface();

// enable markers and set data for them
chart.markers().enabled(true).data(result);

// set x axis labels format
chart
  .xAxis()
  .labels()
  .format(function () {
    return data.x[Math.round(this.value)];
  });.

// set x axis scale maximum
chart.xScale().maximum(data.x.length - 1);
Enter fullscreen mode Exit fullscreen mode

I will now give my chart a title and a bit of padding on all the sides. Lastly, I will reference the <div> created in step one and draw the chart.

// set chart paddings
chart.padding(25, 50, 75, 50);

// set chart title
chart.title('GDP per capita (PPP) in 2006-2020, in USD');

// set container id for the chart
chart.container('container');

// initiate chart drawing
chart.draw();
Enter fullscreen mode Exit fullscreen mode

Initial 3D Surface Chart To Be Customized Next

Voila! A basic functional 3D surface plot is ready!

You can have a look at this basic version of a JavaScript 3D surface plot on AnyChart Playground or check out the code right here.

<!DOCTYPE html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <title>JavaScript Surface Chart</title>
  <script src="https://cdn.anychart.com/releases/8.10.0/js/anychart-core.min.js"></script>
  <script src="https://cdn.anychart.com/releases/8.10.0/js/anychart-surface.min.js"></script>
  <script src="https://cdn.anychart.com/releases/8.10.0/js/anychart-data-adapter.min.js"></script>
  <style type="text/css">   
    html, body, #container {
      width: 100%; height: 100%; margin: 0; padding: 0;
    }
  </style>
  </head>
  <body> 
    <div id="container"></div>
    <script>
      anychart.onDocumentReady(function () {
        anychart.data.loadJsonFile(
          'https://gist.githubusercontent.com/shacheeswadia/b0d6b34a1910359e0e1a8fc0c84019a6/raw/4ab92ca6361f1bc9875d2854e2e1271bc991f86b/surfaceAreaData.json',
          function (data) {
            // processing of the data
            var result = [];
            for (var x = 0; x < data.x.length; x++) {
              for (var y = 0; y < data.y.length; y++) {
                result.push([x, data.y.sort()[y], data.z[x][y]]);
              }
            }

            // create surface chart
            var chart = anychart.surface();

            // enable markers and set data for them
            chart.markers().enabled(true).data(result);

            // set x axis labels format
            chart
              .xAxis()
              .labels()
              .format(function () {
                return data.x[Math.round(this.value)];
              });

            // set x axis scale maximum
            chart.xScale().maximum(data.x.length - 1);

            // set chart paddings
            chart.padding(25, 50, 75, 50);

            // set chart title
            chart.title('GDP per capita (PPP) in 2006-2020, in USD');

            // set container id for the chart
            chart.container('container');

            // initiate chart drawing
            chart.draw();
          }
        );
      });
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Customizing the JS Surface Chart

One of the best parts of using any JS charting library is that you need to write a very minimal amount of code to get a working version of the chart implemented. Moreover, most of the libraries provide options to customize the chart to make it more personalized and informative.

Let me show you how to enhance the JS 3D surface chart to make it more intuitive and aesthetically better:

  • Improve the look and feel of all the axes: Modify the basic settings of the axes Modify the labels of the axes Modify the stroke of the axes
  • Add a color palette
  • Enhance the tooltip

FOR A WALKTHROUGH OF THESE JS SURFACE CHART CUSTOMIZATIONS, CONTINUE READING HERE.

Top comments (0)