Skip to content

Treemap

Uses the d3 treemap layout to create SVG rectangles based on an array of data.

Each rectangle’s area is proportional to its sum of the value field, giving one tile per groupBy id.

Accessor function or string key for the value each rectangle's area is proportional to. Parent rectangles sum their children.

The tiling method that sizes and places the rectangles: the name of a d3-hierarchy method ("squarify" by default) or a custom function with the same signature.

Whether to display the legend. By default, the legend shows when it has more than one entry and each entry stands for a single group (or two groups at most), or when the entries are colored by a category that isn't a groupBy level (see color), in which case each entry is labelled by its category. Pass false to hide it, true to always show it, or a (config, data) => boolean function to decide.

A two-level groupBy ([“parent”, “id”]) nests child rectangles inside their parent groups, so each group occupies its own region of the layout, named in a header strip across its top. Hover a strip to highlight its group, or click it to zoom in.

groupBy

Defines the mapping between data and shape. The value can be a String matching a key in each data point (default is "id"), or an accessor Function that returns a unique value for each data point. Additionally, an Array of these values may be provided if the visualization supports nested hierarchies.

["parent", "id"]

With a three-level groupBy, every level above the tiles gets its own header strip, nested like a market map: sectors, then industries inside them. groupLabelConfig styles the strips (here a dark fill and a 12px font); a group too small for a strip simply gets none. Set groupLabels: false to draw the tiles alone.

Treemap: whether each group above the drawn tiles of a nested groupBy gets a header strip naming it, with its tiles below the strip. Every level above the tiles gets its own strip; a group too small for one gets none. Hovering a strip highlights its group, and clicking it zooms into that group (Back steps out). Defaults to true.

tile: "slice" arranges children as parallel strips instead of the default squarified layout that favors square-ish tiles; use it when preserving order along one axis matters more than aspect ratio.

The tiling method that sizes and places the rectangles: the name of a d3-hierarchy method ("squarify" by default) or a custom function with the same signature.

threshold: 0.0025 merges every state below 0.25% of the total sum into one catch-all rectangle labeled by thresholdName (“States”), keeping tiny slivers from cluttering the layout. Hover it to see the states it holds, largest first. A bucket needs at least two states: a lone small state stays as itself.

The threshold value for bucketing small data points together, as a share of the total. On a stacked Plot, the series whose summed value across every position is under that share of the whole chart's total merge into one series, stacked on top. A bucket needs at least two items, and its tooltips list them. Off (0) by default on Plot charts.

shapeConfig.backgroundImage draws an image inside each shape: here an accessor returns a flag per country (flag builds a small SVG data URI). The image covers the rectangle, is clipped to it, and sits under the labels. Set backgroundImageFit: "contain" to show the whole image instead.

const flag = ([a, b, c]) =>
  `data:image/svg+xml,${encodeURIComponent(
    `<svg xmlns="http://www.w3.org/2000/svg" width="30" height="20"><rect width="10" height="20" fill="${a}"/><rect x="10" width="10" height="20" fill="${b}"/><rect x="20" width="10" height="20" fill="${c}"/></svg>`,
  )}`;

const config = {
  data: [
    {id: "France", value: 68, stripes: ["#0055a4", "#ffffff", "#ef4135"]},
    {id: "Italy", value: 59, stripes: ["#009246", "#ffffff", "#ce2b37"]},
    {id: "Belgium", value: 12, stripes: ["#000000", "#fdda24", "#ef3340"]},
    {id: "Ireland", value: 5, stripes: ["#169b62", "#ffffff", "#ff883e"]},
  ],
  groupBy: "id",
  shapeConfig: {
    backgroundImage: d => flag(d.stripes),
  },
  sum: "value",
};

Click a tile to open its site. on maps event names to handlers: "click.shape" runs for clicks on the chart’s tiles ("click.legend" for legend entries), with the clicked row as its first argument, so each row’s url field opens in a new tab.

on

Event listener for the specified event typenames. Mirrors the core d3-selection behavior.

{}

Hover a tile to mark its value on the colorScale: an extra axis tick marks the value on the color bar and a badge reads it where the tick’s label would sit. With a bucketed scale drawn as swatches (jenks, buckets, quantile), the hover highlight already keeps the value’s swatch lit, so no mark is drawn. Turn it off with colorScaleConfig: {hoverMark: false}, and style it with colorScaleConfig.hoverMarkConfig.

const config = {
  data: [
    {id: "Ash", value: 12},
    {id: "Birch", value: 45},
    {id: "Cedar", value: 23},
    {id: "Elm", value: 67},
    {id: "Fir", value: 89},
    {id: "Maple", value: 34},
    {id: "Oak", value: 150},
    {id: "Pine", value: 56},
  ],
  colorScale: "value",
  colorScaleConfig: {scale: "linear"},
  colorScalePosition: "bottom",
  groupBy: "id",
  sum: "value",
};

Configuration

import {Treemap} from "@d3plus/core";

Extends Viz.

activefalse | function

The active callback function for highlighting shapes.

classNamestring | array.&lt;string&gt; | undefined

CSS classes added to the outermost element this chart or component draws into, next to its fixed d3plus classes, so page CSS can target it: a chart's root <svg class="d3plus-viz"> (its <canvas> with the Canvas renderer) and a standalone component's <svg>. Takes a space-separated string or an array. A new value replaces the classes the previous one added; unset adds none. Tooltips take their own tooltipConfig.className.

colorDefaultscolordefaultsconfig

Overrides the default colors used when assigning fills from data and choosing legible text colors: dark and light (the text colors picked for contrast against a background), missing (null/undefined values), on/off (true/false values), sequential (the anchor hue for magnitude ramps), and scale (the categorical palette, given as a d3 ordinal scale or an array of colors). Keys are merged into the current defaults, and a Viz passes its overrides down to the shapes and components it draws.

configd3plusconfig

Methods that correspond to the key/value pairs and returns this class.

datastring | array.&lt;datapoint&gt; | object

The primary data array used to draw the visualization. The value passed should be an Array of objects or a String representing a filepath or URL to be loaded. The following filetypes are supported: csv, tsv, txt, and json.

If your data URL needs specific headers to be set, an Object with a "url" and "headers" (or any other fetch request option) may also be passed. An Object with any other key is a data row, not a request.

Additionally, a custom formatting function can be passed as a second argument to this method. This custom function will be passed the data that has been loaded, as long as there are no errors. This function should return the final array of obejcts to be used as the primary data array. For example, some JSON APIs return the headers split from the data values to save bandwidth. These would need be joined using a custom formatter.

If you would like to specify certain configuration options based on the yet-to-be-loaded data, you can also return a full config object from the data formatter (including the new data array as a key in the object).

To re-fetch a URL on an interval and redraw when its data changes, set dataPollingInterval; each poll runs the same formatter.

Defaults to an empty array ([]).

facetstring | false | function

Splits the chart into small multiples: a grid of equally sized panels, one per distinct value of this data key or accessor, each drawing the chart for that value's rows. The panels share one legend, color scale, title, and timeline, color each series the same way, and hover, tooltips, and legend clicks apply across all of them. Pass false to draw a single chart. See facetConfig for the grid's layout and shared scales.

facetConfigfacetconfig

Configuration for small multiples (see facet), merged into the current config: - columns / rows: the grid's shape. Chosen by default to make the panels as large as the chart's shape allows. - padding: the space between panels, in pixels (default 20). - sort: panel order — "ascending" (default), "descending", "data" (first appearance), a comparator over facet values, or an Array of values. - scales: "shared" (default) gives every panel of a chart with axes the same x/y domains; "independent" fits each panel to its own rows. Funnel defaults to "independent" (each panel sized to its own widest stage); "shared" sizes every panel against the widest stage across all panels. PolarArea and RadialBar default to "independent" (each panel's rings and ticks fit its own values); "shared" gives every panel the same value domain. - axes: with shared scales, "outer" (default) labels the axes only along the grid's left and bottom edges; "all" labels every panel. An object sets each axis on its own, as in {x: "all", y: "outer"}: every panel labels its x axis, only the left column labels its y axis, and the panels' plot areas line up. BumpChart defaults to "all", and Marimekko labels its categories on every panel and its 0–100% share axis only along the outer edge, even with independent scales. - title: a (value, data) => string function for each panel's title, or false to hide panel titles. - titleConfig: TextBox config for the panel titles (fontSize, fontWeight, fontColor, textAnchor, padding, …).

fontFamilystring | array.&lt;string&gt;

The font family used throughout the visualization.

groupBystring | function | array.&lt;string | function&gt;

Defines the mapping between data and shape. The value can be a String matching a key in each data point (default is "id"), or an accessor Function that returns a unique value for each data point. Additionally, an Array of these values may be provided if the visualization supports nested hierarchies.

groupLabelConfigobjectDefault {}

Treemap: style of the group header strips (see groupLabels). The accessors receive the group's merged row.

groupLabelsbooleanDefault true

Treemap: whether each group above the drawn tiles of a nested groupBy gets a header strip naming it, with its tiles below the strip. Every level above the tiles gets its own strip; a group too small for one gets none. Hovering a strip highlights its group, and clicking it zooms into that group (Back steps out). Defaults to true.

highlightfalse | function

Persistently emphasizes the data points matching the given predicate: the matching marks keep their color while every other mark is de-emphasized to a neutral gray (the "emphasis" form — highlight one series, gray the rest). Unlike hover/active (transient, opacity-based), highlight is a standing state that survives pointer movement. Pass false to clear it.

hoverfalse | function

The hover callback function for highlighting shapes on mouseover.

layoutPaddingunknownDefault 1

The padding, in pixels, inside each parent rectangle and between sibling rectangles.

legendboolean | functionDefault rowLegend

Whether to display the legend. By default, the legend shows when it has more than one entry and each entry stands for a single group (or two groups at most), or when the entries are colored by a category that isn't a groupBy level (see color), in which case each entry is labelled by its category. Pass false to hide it, true to always show it, or a (config, data) => boolean function to decide.

legendSortfunctionDefault function

Custom sort comparator for legend items.

legendTooltiptooltipconfigDefault {tbody: []}

Configuration object for the legend tooltip.

localestring | object

The locale used for all text and number formatting. Supports the locales defined in d3plus-format. The locale can be a complex Object, a locale code (like "en-US"), or a 2-digit language code (like "en"). If a 2-digit code is provided, the "findLocale" function is used to identify the most approximate locale.

onstring

Event listener for the specified event typenames. Mirrors the core d3-selection behavior.

parentunknown

Parent config used by the wrapper.

renderfunction

Draws the visualization given the specified configuration.

rendererboolean | "svg" | "canvas"

Selects which @d3plus/render backend paints the visible output. "svg" = SvgRenderer (default), "canvas" = CanvasRenderer. Boolean arguments both normalize to "svg".

selectstring | htmlelement

The SVG container element as a d3 selector or DOM element. Defaults to undefined.

shapeConfigd3plusconfig

Configuration object with key/value pairs applied as method calls on each shape.

sortfunction | nullDefault function

Comparator for sibling rectangles, given two d3-hierarchy nodes. Defaults to descending by summed value, with any threshold bucket last.

sumstring | functionDefault "value"

Accessor function or string key for the value each rectangle's area is proportional to. Parent rectangles sum their children.

thresholdnumber | function

The threshold value for bucketing small data points together, as a share of the total. On a stacked Plot, the series whose summed value across every position is under that share of the whole chart's total merge into one series, stacked on top. A bucket needs at least two items, and its tooltips list them. Off (0) by default on Plot charts.

thresholdKeystring | function

Accessor for the value used in the threshold algorithm. A stacked Plot defaults to its stacked value.

tile"binary" | "dice" | "resquarify" | "slice" | "sliceDice" | "squarify" | functionDefault treemapSquarify

The tiling method that sizes and places the rectangles: the name of a d3-hierarchy method ("squarify" by default) or a custom function with the same signature.

timestring | false | function

Accessor function or string key for the time dimension of each data point.

timelineDefaultstring | date | array.&lt;string | date&gt;

The starting time or range for the timeline. Can be a single Date/String, or an Array of 2 values representing the min and max.

tooltipConfigtooltipconfigDefault {tbody: [shareRow(viz, "sum")]}

Configuration for the tooltip component.

totalstring | boolean | function

Accessor function or string key for the total value displayed in the visualization.

translatefunction

Defines how informational text strings should be displayed. By default, this function will try to find the string in question (which is the first argument provided to this function) inside of an internally managed translation Object. If you'd like to override to use custom text, simply pass this method your own custom formatting function.