How to Make a Treemap in JavaScript – DEV Community 👩‍💻👨‍💻

admin

image# javascript # webdev # datascience # tutorial Treemap visualizations are widely used in hierarchical data analysis.If you need to build one but have never done that before, you might think the process is somewhat complicated.Well, not necessarily.I decided to make a step-by-step tutorial explaining how to create awesome interactive treemap charts with ease using JavaScript.And you’re gonna love the illustrations!

Are we alone in the universe? A question every one of us has asked ourselves at some point.While we are thinking about the odds of the Earth being the only habitable planet in the universe, or not, one of the things we might consider is how big the universe is.Let’s look at that with the help of treemaps! In this tutorial, we will be visualizing the scale of the 10 largest galaxies in the known universe using the treemapping technique.

So, would you like to know how to quickly build a JS-based treemap chart? Follow me in this stepwise tutorial and learn in an easy, fun way!

What Is a Treemap? Before we get down to the tutorial itself, let’s look at the concept of treemaps.A treemap chart is a popular technique for visualizing hierarchically organized, tree-structured data.

Designed to show at a glance the structure of hierarchy along with the value of individual data points, it makes use of nested rectangles whose size is proportional to the corresponding quantities.

Each branch of the tree is a rectangle, and for sub-branches, there are smaller rectangles nested inside them.Displaying data by color and proximity, treemaps can easily represent lots of data while making efficient use of space and are great for comparing proportions within hierarchies.

The treemap chart type was invented by professor Ben Shneiderman who has given significant contributions in the field of information design and human-computer interaction.Treemaps are used in many data visualization areas and can be found applied in the analysis of stock market data, census systems, and election statistics, as well as in data journalism, hard drive exploration tools, etc.

A Peek at Our JS Treemap Chart So now, we will build a treemap using JavaScript to compare the sizes of the top 10 galaxies in the known universe.Take a look at exactly what we are going to create.

This is what our JS treemap chart will look like by the end of the tutorial.

Let’s start our interstellar journey!

Create a Basic JS Treemap Chart Creating a JavaScript-based treemap chart generally takes four basic steps that are as follows:

Create an HTML page Reference JavaScript files Set data Write some JS treemapping code And don’t worry if you are a novice in HTML, CSS, and JavaScript.We will go through each and every step in detail, and by the end of this tutorial, you will have your own JS treemap ready.

So, the countdown has begun, let’s get our chart ready for launch.

1.Create an HTML Page The first thing we do here is to create a basic HTML page.There, we add an HTML block element (

) — that’s where our treemap chart will be placed — and assign it an ID attribute (for example, let it be “container”) to reference it later in the code.

We should also set some styling for the

.

Let’s define the width and height properties as 100% and margin and padding as 0.You may change this to your liking.

JavaScript Treemap Chart

Enter fullscreen mode

Exit fullscreen mode

2.Reference JavaScript Files Next, we need to reference all the required scripts that will be used to create a treemap chart.

There are multiple JavaScript charting libraries out there to choose from.The fundamental steps of creating interactive data visualizations remain more or less the same with any of them.

Here, for illustration, I am going to use AnyChart — it supports treemaps and has a free version, with the source open on GitHub.

So, to build a treemap chart, we need the ‘core’ and ‘treemap’ modules .Let’s reference both in the head section of the HTML page created in the first step.We will obtain them from the CDN (alternatively, the scripts can be downloaded).

JavaScript Treemap Chart

Enter fullscreen mode

Exit fullscreen mode

3.Set Data Here comes the data.

We will visualize the scale of the top 10 largest galaxies in the known universe.The galaxies are so incredibly vast that they’re measured by how many light-years across they are.A light-year is the distance a beam of light travels in a single Earth year, which equates to approximately 6 trillion miles.

I have already taken the galaxy scale data from Largest.org .

For our chart, the tree structure data will look as follows.The root-level element is ‘Galaxies,’ divided (by galaxy type) into ‘Elliptical’ and ‘Spiral’ as its children, which further have arrays of individual galaxy objects as their own children.

Each galaxy object is provided with key-value properties of name and scale in light-years.For example, {name: “IC 1101”, value: 4 } means the IC 1101 galaxy with its scale being 4,000,000 light-years.Honestly, it’s very hard to comprehend how massive it is.

var dataSet = [ { name : ” Galaxies ” , children : [ { name : ” Elliptical ” , children : [ { name : ” IC 1101 ” , value : 4 }, { name : ” Hercules A ” , value : 15 }, { name : ” A2261-BCG ” , value : 1 }, { name : ” ESO 306-17 ” , value : 1 }, { name : ” ESO 444-46 ” , value : 402200 }, ]}, { name : ” Spiral ” , children : [ { name : ” Rubin’s Galaxy ” , value : 832000 }, { name : ” Comet Galaxy ” , value : 6 }, { name : ” Condor Galaxy ” , value : 522000 }, { name : ” Tadpole Galaxy ” , value : 280000 }, { name : ” Andromeda Galaxy ” , value : 220000 } ]} ]} ];

Enter fullscreen mode

Exit fullscreen mode

4.

Write Some JS Treemapping Code Now, just a few lines of JavaScript code to fuel up our treemap chart.

First, we include the anychart.onDocumentReady() function, which will enclose all the JavaScript code of the treemap ensuring it will execute when the web page is fully loaded and ready.

Enter fullscreen mode

Exit fullscreen mode

Second, we add the data we want to visualize in a treemap chart, from step 3.

Enter fullscreen mode

Exit fullscreen mode

Third, we add the following line to create a treemap from the tree data.

var chart = anychart .treeMap ( dataSet , ” as-tree ” );

Enter fullscreen mode

Exit fullscreen mode

Finally, we add a title, put the chart in the previously defined

container, and display it using the draw command.

chart .

title ( ” The 10 Largest Galaxies in the Known Universe ” ); chart .

container ( ” container ” ); chart .draw ();

Enter fullscreen mode

Exit fullscreen mode

Now our JS treemap is basically ready, and if we stopped at that, it would look something like this:

There are only two tiles visible immediately as the treemap chart is loaded, ‘Elliptical’ and ‘Spiral.’ We can click on those, and they will expand to show their respective children galaxies — that’s what is called a drill-down action.

Why is this happening, just two tiles? Because by default, the maximum depth value is set as 1.It means we can see only one level with its parent at a time.The lower levels are hidden.

On the first level, we have ‘Galaxies’ being divided into ‘Elliptical’ and ‘Spiral,’ so we only see that by default.

Now, what do we do to display all the galaxy tiles at once? It’s very simple.We just need to change the maximum depth value using the maxDepth() function.

chart .maxDepth ( 2 );

Enter fullscreen mode

Exit fullscreen mode

The countdown is over, and our treemap chart is already now!

In this chart, we can see how the galaxies are grouped based on hierarchy, and we can also click on the ‘Elliptical’ or ‘Spiral’ headers at the top to zoom in on their children’s galaxies.

Look at the interactive version of this basic JavaScript treemap chart on JSFiddle or AnyChart Playground .Feel free to play around with it.

You can also check out the full code below.

JavaScript Treemap Chart

Enter fullscreen mode

Exit fullscreen mode

It was quite effortless to create a beautiful JavaScript treemap chart, wasn’t it? Now, you can see at a glance how the scale of the 10 largest galaxies looks and compare them.

The resulting chart already looks very good to me.But, let me show you how you can customize JavaScript treemaps whenever you want more.

Customize the JS Treemap Chart Now, let’s add some aesthetic and functional changes to make our interactive treemap chart even better and more insightful.

A.Change Colors

B.Apply a Linear Color Scale

C.Format Labels and Tooltips

D.

Sort Tiles in Ascending Order

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

Top comments (0) Crown

Sort discussion: Selected Sort Option

Top Most upvoted and relevant comments will be first Latest Most recent comments will be first Oldest The oldest comments will be first Subscribe Personal Trusted User Create template Templates let you quickly answer FAQs or store snippets for re-use.

Submit Preview Dismiss Code of Conduct • Report abuse Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment’s permalink .

Hide child comments as well

Confirm

For further actions, you may consider blocking this person and/or reporting abuse

This post blew up on DEV in 2020:

🚀⚙️ JavaScript Visualized: the JavaScript Engine As JavaScript devs, we usually don’t have to deal with compilers ourselves.However, it’s definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!

Read next Creating fast type-safe polymorphic components Nashe Omirro – Nov 16

Next.js vs WordPress: Does the comparison make sense? Max Ikäheimo – Nov 14

Is it possible to test without code? Yassine Zeriouh – Nov 14

React Hook Form: a unique implementation Romain Trotard – Nov 16

andreykh1985 Follow Joined Jul 11, 2018 More from andreykh1985 How to Create Bubble Maps in JavaScript # javascript # datascience # tutorial # beginners How to Create a Line Chart in JavaScript # javascript # datascience # tutorial # beginners Creating an Interactive Circle Packing Chart in JS # javascript # webdev # datascience # tutorial Once suspended, andreykh1985 will not be able to comment or publish posts until their suspension is removed.

Note:

Submit & Suspend Once unsuspended, andreykh1985 will be able to comment and publish posts again.

Note:

Submit & Unsuspend Once unpublished, all posts by andreykh1985 will become hidden and only accessible to themselves.

If andreykh1985 is not suspended, they can still re-publish their posts from their dashboard.

Note:

Unpublish all posts Once unpublished, this post will become invisible to the public and only accessible to andreykh1985.

They can still re-publish the post if they are not suspended.

Unpublish Post Thanks for keeping DEV Community 👩‍💻👨‍💻 safe.

Here is what you can do to flag andreykh1985:

Make all posts by andreykh1985 less visible andreykh1985 consistently posts content that violates DEV Community 👩‍💻👨‍💻’s code of conduct because it is harassing, offensive or spammy.

Report other inappropriate conduct

Confirm Flag Unflagging andreykh1985 will restore default visibility to their posts.

Confirm Unflag.

Leave a Reply

Your email address will not be published. Required fields are marked *

Next Post

9 Best Knowledge Base Plugins for WordPress (Compared)

Are you looking for a knowledge base plugin for WordPress? A knowledge base plugin lets you easily publish documentation, tutorials, and how-to articles.You can efficiently organize these resources while keeping them apart from your blog and landing pages. In this article, we’ll share some of the best knowledge base plugins […]
9 Best Knowledge Base Plugins for WordPress (Compared)

Subscribe US Now