DEV Community

Cover image for Creating an Interactive Circle Packing Chart in JS
andreykh for AnyChart

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

Creating an Interactive Circle Packing Chart in JS

A circle packing chart is a common data visualization technique for representing hierarchically organized data through nested circles. Due to the similarity to a treemap, which uses nested rectangles for the same purpose, sometimes it is called a circular treemap. Introduced to data analysis by American mathematician William Thurston in 1985, circle packings greatly reveal the hierarchical structure of data.

I want to show how you can easily build an elegant interactive circle packing chart with the help of JavaScript! In this step-by-step tutorial, we will be representing the world’s 100 wealthiest people in 2022 by country and industry, according to Forbes’ list of billionaires. So, get your packings done and get ready as your brain is going to get slightly richer!

Circle Packing Chart That Will Be Created

Let me demonstrate what our JavaScript circle packing chart will look like when finished. And it will be interactive! Once you complete this tutorial, you will be fully capable of quickly visualizing your own data in your own circle packing chart.

JavaScript Circle Packing Chart Built in This Data Visualization Tutorial

Now, let’s proceed to make it!

Basic Circle Packing Chart with JavaScript

Even though it isn’t required, having some prior knowledge of HTML, CSS, and JavaScript would make it especially easier to grasp the concepts. However, even if you are a total newbie, there is no need to panic. By the time we are done, you will have learned how to make a circle packing chart by yourself as we will go over each step in depth.

Any JavaScript chart, including our circle packing diagram, can be created in four general steps:

  1. Prepare a web page.
  2. Include all necessary JS files.
  3. Load your data.
  4. Write some JavaScript charting code.

Let’s explore these steps in more detail to prepare an amazing interactive JS-based circle packing chart.

1. Prepare a web page

First of all, we need a place for the circle packing chart.

Build a web page if you don’t have it yet. There, create a container for the plot by adding an HTML block element with a unique ID. Also, specify some CSS rules for this element to define how the chart should be displayed.

Here’s how my HTML page looks:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Circle Packing Chart in JavaScript</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

In my example, the block element is <div>. Its ID is container. The width and height properties are set to 100%, while margin and padding are set to 0, which will make the circle packing chart appear throughout the entire page; but you are welcome to define all that however you see fit in your situation.

2. Include all necessary JS files

Next, we need all necessary JavaScript files to be referenced in the <head> section.

When you utilize the right data visualization tool, creating a circle packing chart won’t be as difficult or time-consuming as it might be. For this tutorial, I’ve chosen to use AnyChart JS Charts. It is one of a few JavaScript charting libraries that support circle packing charts out of the box and is beginner-friendly because it offers a ton of examples that are ready to use and has thorough documentation.

For adding the required JavaScript files, we have two options: download them locally or use them from a content delivery network (CDN). Let’s opt for the second one. Add the Core and Circle Packing scripts for charting. Plus, if you are going to visualize data from a file, like me in this case, include the Data Adapter module to facilitate the data loading. The JS code itself will be put in the <script> tag in the <body> section (it can be set up in the <head> section, alternatively).

Here’s a look at my current HTML page:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Circle Packing Chart in JavaScript</title>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-circle-packing.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>
      // The JS Circle Packing Chart’s code will be written here.
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

3. Load your data

Now it’s time to add data.

I want to visualize data from Forbes’ ranking of the richest people, Forbes Billionaires 2022, which includes information on their net worth, countries, sources of wealth, and industries. I have already taken the data from the above link on the 100 wealthiest of them and saved it in a JSON file. (Feel free to use other supported data formats, just make sure the way the data is set conforms to the data instructions for circle packing charts.)

To appropriately load the data, get ready to use the anychart.data.loadJsonFile() function. Like this:

anychart.data.loadJsonFile('https://gist.githubusercontent.com/awanshrestha/ff3ae5c08238b1f4f950f022aaad2f6f/raw/3766915befaeea7a32f3d41fdc2ece110e7543d7/circle-packing-chart.json');
Enter fullscreen mode Exit fullscreen mode

Now, only a few lines of JavaScript code remain to complete the circle packing chart!

4. Write some JavaScript charting code

Finally, we need some JavaScript code to create the circle packing chart.

Add the anychart.onDocumentReady() function, which will include the entire chart’s JS code. It makes sure that the code won’t run until the page has completely loaded.

<script>
   anychart.onDocumentReady(function () {
     // The JS Circle Packing Chart's code will be written here.
</script>
Enter fullscreen mode Exit fullscreen mode

Load the JSON data file as shown in Step 3 and add the data.

<script>

  anychart.onDocumentReady(function () {

    // load a json data file
anychart.data.loadJsonFile('https://gist.githubusercontent.com/awanshrestha/ff3ae5c08238b1f4f950f022aaad2f6f/raw/3766915befaeea7a32f3d41fdc2ece110e7543d7/circle-packing-chart.json',
      function(data) {

        // add the data
        var treeData = anychart.data.tree(data, 'as-table');

      }
    );

});

</script>
Enter fullscreen mode Exit fullscreen mode

Use the circlePacking() function to create a circle packing chart instance, passing the data set into it.

// create a circle packing chart instance
var chart = anychart.circlePacking(treeData);
Enter fullscreen mode Exit fullscreen mode

Lastly, give the chart a title, place it in the container that was previously specified, and display it by using the draw() command.

// add a chart title
chart.title("Forbes Top 100 Richest people");
// specify the container element id
chart.container('container')
// initiate the drawing of the chart
chart.draw();
Enter fullscreen mode Exit fullscreen mode

Tada! The JavaScript-based circle packing chart is ready!

A basic circle packing chart built with JavaScript

You can find the interactive version of this simple JavaScript circle packing chart on AnyChart Playground chart along with the source code. Feel free to experiment with it.

I will also put the complete circle packing chart code below for your convenience.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Circle Packing Chart in JavaScript</title>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-circle-packing.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>

      anychart.onDocumentReady(function () {

        // load a json data file
anychart.data.loadJsonFile('https://gist.githubusercontent.com/awanshrestha/ff3ae5c08238b1f4f950f022aaad2f6f/raw/3766915befaeea7a32f3d41fdc2ece110e7543d7/circle-packing-chart.json',
          function(data) {

            // add the data
            var treeData = anychart.data.tree(data, 'as-table');

            // create a circle packing chart instance
            var chart = anychart.circlePacking(treeData);

            // add a chart title
            chart.title("Forbes Top 100 Richest people");

            // specify the container element id
            chart.container('container');

            // initiate the drawing of the chart
            chart.draw();

          }
        );

      });

    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

We can immediately deduce from the circle packing chart that the majority of the top billionaires are from the United States, followed by China. Similar to that, we can also get insights regarding industries along with the net worth amounts.

However, this is only a basic version of the JS circle packing chart. The graphic can be further customized to look much better (still without much hassle).

Advanced Circle Packing Chart with JavaScript

The circle packing diagram created with JS so far already looks pleasing to the eye. But occasionally, decent is insufficient. Additionally, there are instances when you may need to adjust the chart’s appearance and functionality.

Fortunately, you can easily customize the circle packing charts to meet your needs and tastes. Now I will demonstrate some quick customizations you may also want to make to improve the visualization:

A. Customize the tooltip.
B. Customize the appearance.
C. Customize the title.
D. Customize the labels.

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

Top comments (0)