DEV Community

Cover image for Building a Scatter Plot in JavaScript
andreykh for AnyChart

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

Building a Scatter Plot in JavaScript

With data everywhere around us, it is imperative to know how to quickly create visualizations that help reveal trends and patterns in it. Today, let’s learn how to build a scatter chart in just a few lines of simple JavaScript code!

Scatter charts, or scatter plots, are designed to identify a correlation between typically two variables. In such graphics, the data is visualized as a set of points usually displayed as markers. The position of each marker indicates the values of the variables along the horizontal and vertical axes.

In this tutorial, we will be visualizing international and domestic sales of the 1000 highest-grossing Hollywood movies as of January 2022. So, get your popcorn and start watching the JS scatter chart development!

Creating a Scatter Chart with JavaScript

Building interactive scatter charts from scratch can be difficult and time-consuming. But it is not a problem at all if you use JavaScript the right way.

Generally speaking, there are four basic steps you need to take to get a JS-based scatter chart up and running. Here they are.

1. Create a basic HTML page with a container

First of all, we need a web page with a container where our future scatter chart will be displayed.

Create an HTML file (or feel free to open an existing one of your own). Include a block-level element, provide it with a unique id that will be referenced later, and set its width and height. Here’s a basic example of how all this can look:

<html>
  <head>
    <title>JavaScript Scatter 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

As you see, we’ve got a very basic HTML page with a <div> element whose id is set as “container” and both width and height are 100% so that the JavaScript scatter chart is displayed over the entire screen (these values can be specified as per preference and requirement).

2. Include the necessary scripts

Second, include all the scripts needed for creating the plot in the <head> section of the HTML page.

To build this scatter chart, let’s use AnyChart JS Charts. It is a very flexible JavaScript charting library with extensive documentation, a lot of readymade JS chart examples, and integration templates for many popular tech stacks.

The AnyChart JS charting library is modular, and its Base module will be more than enough in this case. The data we will visualize are stored in a JSON file, and the Data Adapter script will let us load it from there in a straightforward manner.

So, we only need to reference these two JS files.

<html>
  <head>
    <title>JavaScript Scatter Chart</title>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-base.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.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>
      // This is the place for the entire JS scatter chart code.
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

3. Connect the data

Third, load the data you want to represent.

In this tutorial, we will use the scatter charting technique to visualize data from the Top 1000 Highest Grossing Movies dataset on Kaggle. I took the sales figures along with the titles of the movies and put them all in a JSON file.

AnyChart supports multiple ways to load data to charts. When it comes to data in a JSON file, for example, it is easy to add it using the loadJsonFile() method:

anychart.data.loadJsonFile(
  "https://gist.githubusercontent.com/shacheeswadia/dceaadd5fb4ea27cd9975ff39e9f98f4/raw/6baac571527d9b13e397cfb3d982d7942246dcc0/scatterPlotData.json",
  function(data) {
    // The main scatter plot visualization code will be here.
  }
);
Enter fullscreen mode Exit fullscreen mode

4. Write the visualization code

Now, let’s get to the main part of having an interactive JS scatter chart appear on our web page. Actually, it will only take a few lines of straightforward code.

Add the anychart.onDocumentReady() function that will enclose all the scatter plotting JavaScript code, making sure that the page is fully loaded before the visualization is executed. Then load the data the way described in the previous step.

anychart.onDocumentReady(function () {
  anychart.data.loadJsonFile(
    "https://gist.githubusercontent.com/shacheeswadia/dceaadd5fb4ea27cd9975ff39e9f98f4/raw/6baac571527d9b13e397cfb3d982d7942246dcc0/scatterPlotData.json",
    function (data) {
      // The following JS code comes here.
    }
  );
});
Enter fullscreen mode Exit fullscreen mode

Next, create a scatter chart instance (using the built-in scatter() function) and define markers (there are various options for the marker type, but let’s adhere to the classic circle shape).

let chart = anychart.scatter();

let marker = chart.marker(data);
marker.type("circle").size(2);
Enter fullscreen mode Exit fullscreen mode

It is important to specify what kind of values are plotted along each axis. So, let’s set the titles for both:

chart.yAxis().title("International sales ($ in millions)");
chart.xAxis().title("Domestic sales ($ in millions)");
Enter fullscreen mode Exit fullscreen mode

Similarly, let’s also title the entire data visualization:

chart.title("Top 1000 Highest Grossing Hollywood Movies: Domestic vs. International Sales");
Enter fullscreen mode Exit fullscreen mode

Now, simply reference the container’s id and command to draw the chart.

chart.container("container");
chart.draw();
Enter fullscreen mode Exit fullscreen mode

That’s it! A beautiful, fully functional, interactive scatter chart is created with just these few lines of JavaScript code and can be embedded as is into any web page or app!

Scatter Chart Initial

The initial version is available on AnyChart Playground. We can see that there is a definite correlation between domestic and international sales, but there are some outliers as well.

JS Scatter Chart Customization

A basic scatter chart is ready. Now, let’s see how we can make it more informative and aesthetically better.

A. Improve the tooltip
B. Modify the scale
C. Add grid lines
D. Aesthetic changes

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

Top comments (0)