Treemap Chart

Overview

A treemap is a visualization that displays hierarchically organized data as a set of nested rectangles, parent elements being tiled with their child elements. The sizes and colors of rectangles are proportional to the values of the data points they represent.

This article explains how to create a basic Treemap chart in AnyChart as well as configure settings that are specific to the type. You can also see the table below to get a brief overview of the Treemap chart's characteristics:

ModulesCore + Treemap
API
Classanychart.charts.TreeMap
DATA
Data Fieldsid, parent, children, name, size, value
Multiple SeriesN/A
OPTIONS
StackedN/A
VerticalN/A
3DN/A
Error BarsN/A
SUPPORTED CHART PLOTS
PolarN/A
RadarN/A
ScatterN/A
StockN/A
RELATED TYPES
Heat Map
Marimekko
Venn
SEE ALSO
Chartopedia: Treemap Chart
General Settings

Modules

The Treemap chart requires adding the Core and Treemap modules:

<script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-core.min.js"></script>
<script src="https://cdn.anychart.com/releases/8.12.0/js/anychart-treemap.min.js"></script>

Learn more: Modules.

Quick Start

To create a Treemap chart, use the anychart.treeMap() chart constructor.

In the sample below, there is a basic Treemap comparing the top 10 most populated European Union countries by their population:

// create data
var data = [
  {name:   "European Union - Top 10 Most Populated Countries", children: [
    {name: "Belgium",        value: 11443830},
    {name: "France",         value: 64938716},
    {name: "Germany",        value: 80636124},
    {name: "Greece",         value: 10892931},
    {name: "Italy",          value: 59797978},
    {name: "Netherlands",    value: 17032845},
    {name: "Poland",         value: 38563573},
    {name: "Romania",        value: 19237513}, 
    {name: "Spain",          value: 46070146},
    {name: "United Kingdom", value: 65511098}  
  ]} 
];

// create a chart and set the data
chart = anychart.treeMap(data, "as-tree");

// set the container id
chart.container("container");

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

Playground

General Settings

In AnyChart there are many settings that are configured in the same way for all chart types, including the Treemap chart (for example, legend and interactivity settings).

Read the overview of general settings: General Settings.

Special Settings


Data

The Treemap chart requires the tree data model. Use the following fields:

  • id to set unique identifiers
  • parent to set parents
  • children to set children
  • name to set names
  • size to set sizes
  • value to set values

Note 1: It is possible to add custom fields to your data - see the Labels and Tooltips section of this article.

Note 2: A Treemap chart can have only one root element.

Colors and sizes of tiles represent the value field. Alternatively, sizes can represent an optional size field, so adding it to the data allows you to show two different parameters instead of one.

Please note: you do not need to specify values and sizes of parent elements - they are calculated automatically. Also note that tiles are sorted by value, but if you add the size field, they are sorted by size.

On the Treemap chart below, the size of each tile represents the population of a country (size), and the color represents the population density (value):

// create data
var data = [
  {name:   "EU - Population Density in Top 10 Most Populated Countries", children: [
    {name: "Belgium",        size: 11443830, value: 378},
    {name: "France",         size: 64938716, value: 119},
    {name: "Germany",        size: 80636124, value: 231},
    {name: "Greece",         size: 10892931, value:  85},
    {name: "Italy",          size: 59797978, value: 203},
    {name: "Netherlands",    size: 17032845, value: 505},
    {name: "Poland",         size: 38563573, value: 126},
    {name: "Romania",        size: 19237513, value:  84}, 
    {name: "Spain",          size: 46070146, value:  92},
    {name: "United Kingdom", size: 65511098, value: 271}  
  ]} 
];

// create a chart and set the data
chart = anychart.treeMap(data, "as-tree");

Playground

Depth and Hints

You can specify how many levels of the hierarchy are shown simultaneously on a chart: use the maxDepth() method.

All elements shown with this method are interactive, and their parents are visualized as headers. The default value is 1, which means that users can see only one level with its parent at a time, and the lower levels are hidden.

The hintDepth() method sets the depth of hints - lines indicating the elements of hidden levels. The elements shown with this method are not interactive; the default value is 0, which means that hints are disabled.

To set the opacity of hints, use hintOpacity().

The following sample demonstrates how to configure the depth of levels shown and the depth and opacity of hints:

// set the maximum depth of levels shown
chart.maxDepth(2);

// set the depth of hints
chart.hintDepth(1);

// set the opacity of hints
chart.hintOpacity(0.7);  

Playground

Sorting Order

By default, tiles of Treemaps are sorted in descending order according to their values. You can sort them in ascending order or disable sorting.

To set the sorting mode, call the sort() method with one of the parameters listed in anychart.enums.Sort:

  • "desc" (default)
  • "asc"
  • "none"

Note: If you add the size field to your data, tiles are sorted by size, not value. If you disable sorting, tiles are arranged according to the order in which they occur in data.

The sample below shows how to set the sorting mode:

// set the sorting mode
chart.sort("asc");

Playground

Appearance

All Points

The appearance settings of a Treemap chart can be configured in three states: normal, hover, and selected. Use the normal(), hovered(), and selected() methods.

Combine them with the following methods:

Also, you can use some other methods from anychart.core.StateSettings.

In this sample, there is a Treemap chart with appearance settings configured:

// configure the visual settings of the chart
chart.hovered().fill("gray", 0.4);
chart.selected().fill("gray", 0.6);
chart.selected().hatchFill("forward-diagonal", "gray", 2, 20);
chart.normal().stroke("gray");
chart.hovered().stroke("gray");
chart.selected().stroke("gray", 2);

Playground

Individual Points

It is possible to configure the appearance of each tile individually - use extra data fields corresponding to the methods mentioned above:

// create data
var data = [
  {name:   "European Union", children: [
    {name: "Belgium",        value: 11443830, fill: "#ffcc00"},
    {name: "France",         value: 64938716, fill: "#ff6600"},
    {name: "Greece",         value: 10892931, fill: "#ffcc00"},
    {name: "Italy",          value: 59797978, fill: "#ff6600"},
    {name: "Netherlands",    value: 17032845, fill: "#ffcc00"},
    {name: "Poland",         value: 38563573, fill: "#ff9933"},
    {name: "Romania",        value: 19237513, fill: "#ffcc00"}, 
    {name: "Spain",          value: 46070146, fill: "#ff9933"},
    {name: "United Kingdom", value: 65511098, fill: "#ff6600"},
    {name: "Germany",        value: 80636124,
     normal:   {fill: "#ff0000", stroke: "4 #b30059"},
     hovered:  {fill: "#ff0000", stroke: "5 white"},
     selected: {fill: "#b30059", stroke: "5 white"}
    }
  ]} 
];

// create a chart and set the data
chart = anychart.treeMap(data, "as-tree");

Playground

Color Scale

By default, the color scale of a Treemap chart is ordinal, and tiles are colored in the colors of the default palette. Color ranges are set automatically.

Ordinal

To customize the ordinal color scale, you should create it explicitly by using the ordinalColor() constructor.

Combine it with ranges() to set heat ranges (two or more) you want to be marked by different colors. Then you can set a color for each of these ranges by using the colors() method. Please note that if you do not specify colors and ranges, the default settings of the ordinal color scale are used.

To set your scale as the color scale of the chart, use the colorScale() method.

Optionally, you can use colorRange() to enable a color range - a special interactive element representing the color scale. With the ordinal color scale, the color range shows the ranges and their colors. You can find the available settings here: anychart.core.ui.ColorRange.

This sample shows a Treemap with an ordinal color scale and a color range:

// create and configure a color scale.
var customColorScale = anychart.scales.ordinalColor();
customColorScale.ranges([
  {less: 20000000},
  {from: 20000000, to: 50000000},
  {from: 50000000, to: 70000000},
  {greater: 70000000}
]);
customColorScale.colors(["lightgray", "#9ed1de", "#00ccff", "#ffcc00"]);

// set the color scale as the color scale of the chart
chart.colorScale(customColorScale);

// add a color range
chart.colorRange().enabled(true);
chart.colorRange().length("90%");

Playground

Linear

To create a linear color scale, use the linearColor() constructor.

Then call colors() to set two colors, the first one indicating 0, and the second one indicating the maximum heat. Tiles are colored automatically in different mixtures of these two colors, and if you do not specify them, the default colors of the linear color scale are used.

Finally, call colorScale() to set your scale as the color scale of the chart.

Optionally, you can use colorRange() to add a color range - a special interactive element representing the color scale. With the linear color scale, it looks like a gradient from the first to the second color. You can find the available settings here: anychart.core.ui.ColorRange.

In the following sample, there is a Treemap with a linear color scale and a color range:

// create and configure a color scale.
var customColorScale = anychart.scales.linearColor();
customColorScale.colors(["#00ccff", "#ffcc00"]);

// set the color scale as the color scale of the chart
chart.colorScale(customColorScale);

// add a color range
chart.colorRange().enabled(true);
chart.colorRange().length("90%");

Playground

Labels and Tooltips

Labels are text or image elements that can be placed anywhere on any chart (you can enable them on a whole series or in a single point). For text labels, font settings and text formatters are available.

A Tooltip is a text box displayed when a point on a chart is hovered over. There is a number of visual and other settings available: for example, you can edit the text by using font settings and text formatters, change the style of background, adjust the position of a tooltip, and so on.

Tokens

To change the text of labels, combine the labels() and format() methods with tokens.

To configure tooltips, do the same with the tooltip() and format() methods.

Here is the list of tokens that work with the Treemap chart:

  • {%id}
  • {%name}
  • {%size}
  • {%value}

Please note that values and sizes of parent elements are calculated automatically, so you do not need to specify them in data - the {%value} and {%size} tokens work anyway.

Also, you can always add a custom field to your data and use a custom token corresponding to it.

This sample shows how to work with tokens. Along with regular tokens, a custom token {%capital} is used:

// create data
var data = [
  {name:   "European Union - Top 10 Most Populated Countries", children: [
    {name: "Belgium",        value: 11443830, capital: "Brussels" },
    {name: "France",         value: 64938716, capital: "Paris"    },
    {name: "Germany",        value: 80636124, capital: "Berlin"   },
    {name: "Greece",         value: 10892931, capital: "Athens"   },
    {name: "Italy",          value: 59797978, capital: "Rome"     },
    {name: "Netherlands",    value: 17032845, capital: "Amsterdam"},
    {name: "Poland",         value: 38563573, capital: "Warsaw"   },
    {name: "Romania",        value: 19237513, capital: "Bucharest"}, 
    {name: "Spain",          value: 46070146, capital: "Madrid"   },
    {name: "United Kingdom", value: 65511098, capital: "London"   }  
  ]} 
];

// create a chart and set the data
chart = anychart.treeMap(data, "as-tree");

// enable HTML for labels
chart.labels().useHtml(true);

// configure labels
chart.labels().format(
  "<span style='font-weight:bold'>{%name}</span><br>{%value}"
);

// configure tooltips
chart.tooltip().format(
  "population: {%value}\ncapital: {%capital}"
);

Playground

Formatting Functions

To configure labels and tooltips, you can use formatting functions and the following fields:

  • name
  • size
  • value

Values and sizes of parent elements are calculated automatically, so you do not need to specify them in data.

You can also add a custom field to your data and refer to it by using the getData() method.

The sample below demonstrates how to work with formatting functions. Along with regular fields, a custom field capital is used:

// create data
var data = [
  {name:   "European Union - Top 10 Most Populated Countries", children: [
    {name: "Belgium",        value: 11443830, capital: "Brussels" },
    {name: "France",         value: 64938716, capital: "Paris"    },
    {name: "Germany",        value: 80636124, capital: "Berlin"   },
    {name: "Greece",         value: 10892931, capital: "Athens"   },
    {name: "Italy",          value: 59797978, capital: "Rome"     },
    {name: "Netherlands",    value: 17032845, capital: "Amsterdam"},
    {name: "Poland",         value: 38563573, capital: "Warsaw"   },
    {name: "Romania",        value: 19237513, capital: "Bucharest"}, 
    {name: "Spain",          value: 46070146, capital: "Madrid"   },
    {name: "United Kingdom", value: 65511098, capital: "London"   }  
  ]} 
];

// create a chart and set the data
chart = anychart.treeMap(data, "as-tree");

// enable HTML for labels
chart.labels().useHtml(true);

// configure labels
chart.labels().format(function() {
  var population = Math.round(this.value/100000)/10;
  return "<span style='font-weight:bold'>" + this.name + 
         "</span><br>" + population + " mln";
});

// configure tooltips
chart.tooltip().format(function() {
  var population = Math.round(this.value/100000)/10;
  return "population: " + population +
         " mln\ncapital: " + this.getData("capital");
});

Playground

Font Size

The font size of labels can be automatically adjusted according to the size of tiles - use labels() with adjustFontSize() and true as a parameter to enable this mode:

/* adjust the font size of labels
according to the size of tiles */
chart.labels().adjustFontSize(true);

Playground

Headers

All Headers

By default, parent elements of the currently shown levels are visualized as headers. To disable or enable them, call the headers() method with false or true as a parameter:

// disable headers
chart.headers(false);

You can limit the maximum height of headers, which might be necessary in case your chart is small or its size is dynamically changing. Call the maxHeadersHeight() method and set the maximum height either in pixels (25 by default) or as a percentage:

//set the maximum height of headers
chart.maxHeadersHeight("20%");

The text and font of headers can be configured in the normal and hover states: combine the normal() and hovered() methods with headers().

Changing the default text of headers is similar to configuring labels and tooltips. You should use the format() method with tokens or formatting functions:

// configure the text of headers in the hovered state
chart.hovered().headers().format("{%value}");

To configure the font of headers, use methods listed in anychart.core.ui.LabelsFactory:

// configure the font of headers
chart.normal().headers().fontColor("#990000");
chart.normal().headers().fontSize("14");
chart.normal().headers().fontWeight('bold');
chart.hovered().headers().fontColor("#000099");

The following sample demonstrates how to disable/enable headers; their text is customized in the hovered state, and font settings are changed in all states:

Playground

Individual Headers

Each header can be configured individually by adding the header field to the data:

// create data
var data = [
  {name:     "Slavic Languages",
   normal:  {header: {
                      format: "{%name} ({%value} Total)",
                      fontColor: "#990000",
                      fontSize: "14",
                      fontWeight: "bold"
                     }
            },
   hovered: {header: {fontColor: "#000099"}},
   children: [
    {name:   "East Slavic", header: null, children: [
      {name: "Russian",        value: 150000000},
      {name: "Ukrainian",      value:  45000000},
      {name: "Belarusian",     value:   3200000}
    ]},
    {name:   "West Slavic", header: null, children: [
      {name: "Polish",         value:  55000000},
      {name: "Czech",          value:  10600000},
      {name: "Slovak",         value:   5200000}
    ]},
    {name:   "South Slavic", header: null, children: [
      {name: "Serbo-Croatian", value:  21000000},
      {name: "Bulgarian",      value:   9000000},
      {name: "Slovene",        value:   2500000},
      {name: "Macedonian",     value:   1400000}
    ]}  
  ]} 
];

// create a chart and set the data
chart = anychart.treeMap(data, "as-tree");

Playground

Display Mode

By default, the text of a header is not shown if it does not fit its height. However, you can hide such text or always show the text of headers. To set the display mode of headers, call the headersDisplayMode method with one of the parameters listed in anychart.enums.LabelsDisplayMode:

  • "alwaysShow" (default)
  • "clip"
  • "drop"

The sample below shows how to change the display mode, which is initially set to "drop":

// set the display mode of headers
chart.headersDisplayMode("drop");

Playground

Interactivity

Drilldown

The Treemap chart is interactive by default. It comes with a built-in drilldown feature: if you click on an element, you drill down to its children, and if you click on a header, you drill up a level. This behavior can be modified - use the following methods:

Note: By default it is also possible to drill down or up from the context menu: right-click on a tile or a header and select "Drill Down To" or "Drill Up" in the menu - if, of course, these options are available for the element.

Sometimes you might also need to perform a search in the data with the search() method of the anychart.data.Tree class (see the Tree Data Model article to learn more about operating tree-like data). For example, if you want to drill down to a particular item in the data tree, call search() to get the item and drillTo() to drill down to it. For drilling up, call drillUp():

/* locate an item in the data tree
and get it as an object */
var item = treeData.search("name", "Lvl 3-4");

// drill down to the item
chart.drillTo(item);

// drill up
chart.drillUp();

This sample shows how to drill down to a particular item, drill up, and add the drilldown path to the title of the chart by using a custom function:

Playground

Disabling Drilldown

To disable the drilldown feature, you should add an event listener to your chart. Use the listen() method and specify the event type - drillchange:

// disable the drilldown feature
chart.listen("drillchange", function(e){
  return false;
});

Playground