How to Create Circle Packing Chart with JS
Tags: javascript, beginners, webdev, tutorial
Published: 2022-03-20 09:35:51

**_A clear step-by-step guide for building an interactive JS Circle Packing Chart to visualize the top 100 most streamed songs on Spotify._**

Want to learn to visualize hierarchical data in stunning circle packing charts that can be added to a web page or app in a hassle-free manner? Don’t feel overwhelmed and just follow my stepwise data visualization tutorial! Using a cool example of data on the top 100 most streamed songs on Spotify, I will show you how to easily create and customize a great-looking interactive circle packing chart with JavaScript.

## What Is a Circle Packing Chart

Let me start by giving you a brief about what a circle packing chart is and how it is used.

Also known as a circular tree, a circle packing chart is basically a treemap showcasing hierarchical data, where circles denote nodes and sub-nodes are circles inside the node circle.

The size of the circle denotes the value of the node.

The circular packing representation denotes hierarchy well, providing a convenient visual breakdown by groups and subgroups.

## Previewing the Circle Packing Chart That Will Be Produced

Take a look at what I am going to build — the final JS circle packing chart that will be created by the end of the tutorial — and come along on this musical ride!

![The JavaScript-based circle-packing chart built along the tutorial](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/54j51pwlchh62a22xzbq.png)

## Building a JS Circle Packing Chart in 4 Simple Steps

An embeddable circle packing chart looks exciting but challenging to create. However, there are many [JavaScript charting libraries](https://en.wikipedia.org/wiki/Comparison_of_JavaScript_charting_libraries) specifically designed to help everyone build various data visualizations. And once you’ve found one which provides a built-in circle packing option out of the box, it is usually pretty quick and straightforward to get such an interactive chart conjured up even if you are a beginner with (yet) limited coding skills.

Technically, the steps, which the entire process of creating a circle packing data visualization consists of, remain more or less the same with any JS charting library. In this tutorial, I will be using [AnyChart](https://www.anychart.com/) for illustration. It is pretty easy to start off, with detailed [documentation](https://docs.anychart.com/) and many ready-to-use [examples](https://www.anychart.com/products/anychart/gallery/) that can work as a good starting point for quickly building a chart of any type, including this one. Also important, the library is free for non-commercial use.

So, the basic steps to create a JS Circle Packing Chart number four and are as follows:

1. Make an HTML page for the chart.
2. Include the necessary JS files.
3. Add the data.
4. Write the required JavaScript code for drawing the chart.

### 1. Create an HTML page

The first thing I do is create a basic HTML page where the chart will be placed. Next, I create an HTML block element, `div` and assign it an ID attribute like “container” to easily identify it later in the code.

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

I define the styling of the block such that the chart renders over the whole page by giving the height and width attributes the value of 100%. Feel free to specify it the way you want to do your task, of course.

### 2. Include the necessary JavaScript files

Then, I need to add the scripts I am going to use to create the circle packing chart I want to develop. It is usually possible to reference the necessary files from the CDN of the library you are using or download them to your local machine.

To create this chart in this tutorial, I am employing the AnyChart library. It has a modular structure that makes it easy to only connect the chart types and features you require at the moment, reducing the size of the running JavaScript code. In this case, I need the [core](https://docs.anychart.com/Quick_Start/Modules#core) module together with the specific [circle packing](https://docs.anychart.com/Quick_Start/Modules#circle_packing) module. So I include both in the `head` section of the HTML page created in the first step.

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript Circle Packing Chart</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>
      // All the code for the JS Circle Packing Chart will be here.
    </script>
  </body>
</html>
```

### 3. Add the data

I decided to visualize the 100 most streamed songs on Spotify using a dedicated dataset from [Kaggle](https://www.kaggle.com/pavan9065/top-100-most-streamed-songs-on-spotify). I reworked the data a little bit to make it look the way I need and saved it in a [JSON file](https://gist.githubusercontent.com/shacheeswadia/17dc3b3d4ac9b63ac5ac6833944f3a94/raw/07c4bec103d22ec2824453a33d41868fd476db3d/dataPackedCircles.json).

To load the data from the JSON file, I will utilize a handy module called [Data Adapter](https://docs.anychart.com/Quick_Start/Modules#data_adapter). So I include it in the list of the referenced scripts in the `head` section and use the `anychart.data.loadJsonFile` function to add this data file in the code.

Now that all the preparations are done, let’s get on to the last step for creating this impressive, interactive, JS-based packed circle chart!

### 4. Write the JavaScript code for your chart

Some background knowledge of web development technologies like HTML and JavaScript is always an advantage when creating visualizations and writing code that may seem complicated. However, it can take just as few as about 6 to 7 lines of code to create a circle packing chart this way. So it is not going to be complicated at all anyway. Isn’t that music to your ears?

Initially, I add a function that encloses all the code, ensuring it is executed once the page is ready. Then I include the data inside this function.

Now I define a function with the data parameter and map the data using the `data.tree` function. I add the mapped data to the `circlePacking` function.

```javascript
anychart.onDocumentReady(function () {
  anychart.data.loadJsonFile('https://gist.githubusercontent.com/shacheeswadia/17dc3b3d4ac9b63ac5ac6833944f3a94/raw/07c4bec103d22ec2824453a33d41868fd476db3d/dataPackedCircles.json',
    function(data) {
      var treeData = anychart.data.tree(data, 'as-table');
      var chart = anychart.circlePacking(treeData);
    }
  );
});
```

Finally, I also make a title, add a reference to the previously defined container, and draw the resulting circle packing chart.

```javascript
anychart.onDocumentReady(function () {
  anychart.data.loadJsonFile('https://gist.githubusercontent.com/shacheeswadia/17dc3b3d4ac9b63ac5ac6833944f3a94/raw/07c4bec103d22ec2824453a33d41868fd476db3d/dataPackedCircles.json',
    function(data) {

      // add 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("Top 100 most streamed songs on Spotify by genre")
      
      chart.container('container');
      chart.draw();
    
    }
  );
});
```

Tada! A fully functional circle packing chart is built with so little effort!

![Basic JavaScript Circle Packing Chart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trfhjlpfws474ojoar5g.png)

The pop genre is clearly visible as the most popular among Spotify’s 100 most streamed songs. I am more of a dance genre person myself, and you may be a rock or rhythm and blues fan. But unsurprisingly, pop and hip-hop are the definite crowd favorites.

You can find the entire code of this basic JavaScript packed circle chart on [CodePen](https://codepen.io/shacheeswadia/pen/ExwXmOd) [and on [AnyChart Playground](https://playground.anychart.com/dY0R0BWp/).)

## Customizing a JS Circle Packing Chart

A. Color modification
B. Title improvement
C. Tooltip formatting

**FOR A WALKTHROUGH OF THESE JS STOCK CHART CUSTOMIZATIONS, CONTINUE READING [HERE](https://www.anychart.com/blog/2022/03/15/circle-packing-chart-js/).**

**MORE JAVASCRIPT CHARTING TUTORIALS ARE AVAILABLE [HERE](https://www.anychart.com/blog/category/javascript-chart-tutorials/).**