Creating Circle Packing Chart with JavaScript

September 8th, 2022 by Awan Shrestha

Circle Packing Chart on a web pageA 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>

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>

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');

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>

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>

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);

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();

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


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>

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:

  1. Customize the tooltip.
  2. Customize the appearance.
  3. Customize the title.
  4. Customize the labels.

A. Customize the tooltip

When we hover over the circles, net worth values are shown. Let’s customize the tooltip so that it contains more information.

chart
  .tooltip()
  .useHtml(true)
  .format(function () {
    var src = this.item.get('industry');
    if (src) {
      return '<div>'
        + '<span>Name: ' + this.name + '</span><br/>'
        + '<span>Net worth in billions USD:' + this.value + '</span><br/>'
        + '<span>Source: ' + this.item.get('source') + '</span>'
        + '</div>'
    }
    return '<span>Total net worth: ' + this.value.toFixed(2) + ' billion USD</span>';
  });

Now we can clearly see the names, net worth, and sources of wealth for the billionaires’ circles, as well as total net worth values for industry and country groups.

B. Customize the appearance

The background color of the chart is white by default. Let’s change it to gray. It can be easily done using the background() function.

Let’s also slightly increase the thickness of the circles’ borders using the stroke() function.

// customize the background
chart.background('#f6f6f6');
// customize the stroke
chart
  .stroke(function () {
    return {
      thickness: 1,
    };
  });
// customize the stroke in the hovered state
chart
  .hovered()
  .stroke(function () {
    return {
      thickness: 2,
    };
  });


This JS circle packing’s interactive version is available on AnyChart Playground. Change the colors as you prefer.

C. Customize the title

The chart title can be easily enhanced. Follow me as I simply enable HTML and change the font color, size, and weight:

chart
  .title()
  .enabled(true)
  .useHtml(true)
  .text(
    '<span style = "color: #112B3C; font-weight: 600; font-size: 18px;">100 Richest People, According to Forbes</span>'
  );

This is how the circle packing plot looks after this title enhancement:

D. Customize the labels

At the time being, the names of the countries are displayed in the default format. Let’s customize them to make them appear inside boxes in a more elegant manner:

chart
  .labels()
  .fontSize('14')
  .fontColor('#696969')
  .textShadow('none')
  .anchor('center-top').offsetY('-3%');
 
chart.labels()
  .background()
  .enabled(true)
  .fill("#f6f6f6 0.8")
  .stroke("#888888")
  .corners(5);

The circle packing chart looks very classy and beautiful now. Why wouldn’t it? After all, it is being used to visualize people with billions of worth!


The complete source code for this final JavaScript circle packing chart is available below, as well as on AnyChart Playground.

<!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);
    
            // customize the tooltip
            chart
              .tooltip()
              .useHtml(true)
              .format(function () {
                var src = this.item.get('industry');
                if (src) {
                  return '<div>'
                    + '<span>Name: ' + this.name + '</span> <br/>'
                    + '<span>Net worth in Billions: ' + this.value + '</span> <br/>'
                    + '<span>Source: ' + this.item.get('source') + '</span>'
                    + '</div>' 
                }
                return '<span>' + this.value.toFixed(2) + ' Billion Dollars </span>';
              });
 
            // add a chart title
            chart
              .title()
              .enabled(true)
              .useHtml(true)
              .text(
                '<span style = "color: #112B3C;font-weight:600;font-size:18px;">Forbes Top 100 Richest People</span>'
              );
    
            // customize the appearance
            chart.background('#f6f6f6');
            chart
              .hovered()
              .stroke(function () {
                return {
                  thickness: 2,
                };
              });
            chart
              .stroke(function () {
                return {
                  thickness: 1,
                };
              });
    
            // customize the labels (country names)
            chart
              .labels()
              .fontSize('14')
              .fontColor('#696969')
              .textShadow('none')
              .anchor('center-top').offsetY('-3%');
 
            chart.labels()
              .background()
              .enabled(true)
              .fill("#f6f6f6 0.8")
              .stroke("#888888")
              .corners(5);	
      
            // specify the container element id
            chart.container('container');
    
            // initiate the drawing of the chart
            chart.draw();
    
          }
        );

      });
 
    </body>
  </script>
</html>

Conclusion

Fantastic! Our JavaScript circle packing chart has been constructed. And it’s been an easy process, right? Now, go ahead and create your own JavaScript circle packing chart visualization! The circle packing chart documentation and circle packing chart examples are at your service for further instructions and inspiration, respectively.

Additionally, there are a ton of additional chart types available and don’t be afraid to look at them. You’ll be amazed you can also build them in JS with ease!

Finally, please don’t hesitate to ask for queries or make suggestions. And I’m looking forward to seeing the JavaScript circle packing charts you will create!


We are thankful to Awan Shrestha for contributing this awesome Circle Packing Chart tutorial!

Don’t miss out on our JavaScript charting tutorials for other chart types.

Ready to write a cool guest post like this for our blog? Please get in touch to tell us about your ideas!



Comments (1)

*