React Treemap Chart

Creates a React Treemap Chart using SciChart.js, by leveraging the FastRectangleRenderableSeries and d3-hierarchy.js's layout algorithms to define rectangle positions based on total value

Fullscreen

Edit

 Edit

Docs

drawExample.ts

index.tsx

theme.ts

Copy to clipboard
Minimise
Fullscreen
1import {
2    SciChartSurface,
3    NumericAxis,
4    NumberRange,
5    IFillPaletteProvider,
6    EFillPaletteMode,
7    EStrokePaletteMode,
8    IPointMetadata,
9    parseColorToUIntArgb,
10    IStrokePaletteProvider,
11    EVerticalTextPosition,
12    EHorizontalTextPosition,
13    MouseWheelZoomModifier,
14    ZoomExtentsModifier,
15    ZoomPanModifier,
16    EDataLabelSkipMode,
17    EMultiLineAlignment,
18    FastRectangleRenderableSeries,
19    EResamplingMode,
20    EColumnMode,
21    EColumnYMode,
22    XyxyDataSeries,
23    RectangleSeriesDataLabelProvider,
24    IRectangleSeriesDataLabelProviderOptions,
25    formatNumber,
26    ENumericFormat,
27} from "scichart";
28import { appTheme } from "../../../theme";
29
30import { stratify, treemap } from "d3-hierarchy";
31// choose in between one of the two
32// const d3 = require("./d3-hierarchy.js");
33
34type RectangluarNode = {
35    x0: number;
36    y0: number;
37    x1: number;
38    y1: number;
39    data: TTreemapDataItem;
40};
41
42type TTreemapDataItem = {
43    /**
44     * Unique name of the company
45     */
46    name: string;
47    /**
48     * Short name of the company - optional
49     */
50    shortName?: string;
51    /**
52     * Parent node name
53     */
54    parent: string;
55    /**
56     * Number of Billions the company is worth
57     */
58    value: number;
59    /**
60     * Percentage gained / lost in the selected period
61     */
62    progress?: number;
63};
64
65/**
66 * PaletteProvider for the {@link TreemapRenderableSeries} to manage the colors of rectangles
67 */
68class StockTreemapPaletteProvider implements IStrokePaletteProvider, IFillPaletteProvider {
69    public readonly fillPaletteMode = EFillPaletteMode.SOLID;
70    public readonly strokePaletteMode: EStrokePaletteMode = EStrokePaletteMode.SOLID;
71
72    private _red: number = parseColorToUIntArgb(appTheme.VividRed);
73    private _green: number = parseColorToUIntArgb(appTheme.VividGreen);
74    private _gray: number = 0x404040;
75
76    private _minValue: number = -20;
77    private _maxValue: number = 20;
78
79    constructor({ minValue, maxValue }: { minValue: number; maxValue: number }) {
80        this._minValue = minValue ?? this._minValue;
81        this._maxValue = maxValue ?? this._maxValue;
82    }
83
84    public onAttached(): void {}
85    public onDetached(): void {}
86
87    public overrideFillArgb(
88        _xValue: number,
89        _yValue: number,
90        _index: number,
91        _opacity?: number,
92        metadata?: IPointMetadata
93    ): number | undefined {
94        const percentage = (metadata as unknown as TTreemapDataItem).progress;
95
96        // Handle 0% case explicitly to avoid division issues
97        if (percentage === 0) return this._gray;
98
99        let t: number;
100        let startColor: number;
101        let endColor: number;
102
103        if (percentage > 0) {
104            t = Math.min(percentage / this._maxValue, 1);
105            startColor = this._gray;
106            endColor = this._green;
107        } else {
108            t = Math.min(percentage / this._minValue, 1);
109            startColor = this._gray;
110            endColor = this._red;
111        }
112
113        // Extract ARGB components from colors
114        const getComponents = (color: number) => ({
115            a: (color >>> 24) & 0xff,
116            r: (color >>> 16) & 0xff,
117            g: (color >>> 8) & 0xff,
118            b: color & 0xff,
119        });
120
121        const start = getComponents(startColor);
122        const end = getComponents(endColor);
123
124        // Interpolate each component
125        const interp = (s: number, e: number) => Math.round(s + (e - s) * t);
126        const a = interp(start.a, end.a);
127        const r = interp(start.r, end.r);
128        const g = interp(start.g, end.g);
129        const b = interp(start.b, end.b);
130
131        // Recombine to ARGB
132        return (a << 24) | (r << 16) | (g << 8) | b;
133    }
134
135    public overrideStrokeArgb(
136        _xValue: number,
137        _yValue: number,
138        _index: number,
139        _opacity?: number,
140        metadata?: IPointMetadata
141    ): number | undefined {
142        const fill = this.overrideFillArgb(_xValue, _yValue, _index, _opacity, metadata);
143
144        if (fill) {
145            const brightnessFactor = 1.6;
146            // Extract RGB components
147            let r = (fill >> 16) & 0xff;
148            let g = (fill >> 8) & 0xff;
149            let b = fill & 0xff;
150            // Increase brightness and clamp to the max 255
151            r = Math.min(255, Math.round(r * brightnessFactor));
152            g = Math.min(255, Math.round(g * brightnessFactor));
153            b = Math.min(255, Math.round(b * brightnessFactor));
154            // Set a higher alpha for more "pop"
155            const newAlpha = 0x88;
156            return (newAlpha << 24) | (r << 16) | (g << 8) | b;
157        }
158        return undefined;
159    }
160}
161
162/**
163 * DataLabelProvider for the {@link TreemapRenderableSeries} to manage the labels of rectangles
164 * in the treemap - the bigger the rectangle, the more information is shown
165 */
166class TreemapDataLabelProvider extends RectangleSeriesDataLabelProvider {
167    constructor(options?: IRectangleSeriesDataLabelProviderOptions) {
168        super(options);
169    }
170
171    // Override "getText" method to provide dynamic text based on rectangle size
172    getText(state: any): string {
173        const metadata = state.getMetaData() as TTreemapDataItem;
174        const colWidth = state.columnWidth; // width updates with scroll
175
176        // No label for items without value
177        if (metadata.value === null || metadata.value === undefined) {
178            return null;
179        }
180
181        // Different text formats based on available space
182        if (metadata.value * colWidth > 30000) {
183            return `${metadata.name}` + `\n${formatNumber(metadata.progress, ENumericFormat.Decimal, this.precision)}%`;
184        }
185        if (metadata.value * colWidth > 15000) {
186            return (
187                `${metadata.shortName || metadata.name}` +
188                `\n${formatNumber(metadata.progress, ENumericFormat.Decimal, this.precision)}%`
189            );
190        }
191        if (metadata.value * colWidth > 1500) {
192            return `${(metadata.shortName || metadata.name).slice(0, 1)}`;
193        }
194        return null; // No label for small rectangles
195    }
196}
197
198const WIDTH = 15;
199const HEIGHT = 10;
200const RAW_DATA: TTreemapDataItem[] = [
201    { name: "Technology", parent: "", value: null },
202
203    { name: "Apple", parent: "Technology", value: 4000, progress: 16.2, shortName: "AAPL" },
204    { name: "Microsoft", parent: "Technology", value: 3000, progress: 3.2, shortName: "MSFT" },
205    { name: "NVIDIA", parent: "Technology", value: 4000, progress: 10.5, shortName: "NVDA" },
206    { name: "Alphabet (Google)", parent: "Technology", value: 2185, progress: 0.8, shortName: "GOOG" },
207    { name: "Amazon (AWS)", parent: "Technology", value: 1800, progress: 9.5, shortName: "AMZN" },
208    { name: "Meta (Facebook)", parent: "Technology", value: 1569, progress: 13.7, shortName: "META" },
209    { name: "TSMC", parent: "Technology", value: 600, progress: 17.9, shortName: "TSM" },
210    { name: "Broadcom", parent: "Technology", value: 974, progress: -9.5, shortName: "AVGO" },
211    { name: "Samsung", parent: "Technology", value: 500, progress: -3.1, shortName: "SSNLF" },
212    { name: "Intel", parent: "Technology", value: 200, progress: -18.5, shortName: "INTC" },
213    { name: "AMD", parent: "Technology", value: 180, progress: 7.8, shortName: "AMD" },
214    { name: "Salesforce", parent: "Technology", value: 295, progress: 9.2, shortName: "CRM" },
215    { name: "Adobe", parent: "Technology", value: 193, progress: 12.7, shortName: "ADBE" },
216    { name: "Qualcomm", parent: "Technology", value: 160, progress: -1.9, shortName: "QCO" },
217    { name: "IBM", parent: "Technology", value: 140, progress: -0.5, shortName: "IBM" },
218    { name: "Oracle", parent: "Technology", value: 475, progress: 2.4, shortName: "ORCL" },
219    { name: "Sony", parent: "Technology", value: 120, progress: -18.5, shortName: "SONY" },
220    { name: "Cisco", parent: "Technology", value: 110, progress: 17.2, shortName: "CSC" },
221    { name: "Uber", parent: "Technology", value: 90, progress: 15.0, shortName: "UBR" },
222    { name: "Spotify", parent: "Technology", value: 80, progress: -5.6, shortName: "SPOT" },
223    { name: "Zoom", parent: "Technology", value: 70, progress: -8.0, shortName: "ZM" },
224    { name: "Dropbox", parent: "Technology", value: 60, progress: 1.0, shortName: "DBX" },
225    { name: "Snap", parent: "Technology", value: 50, progress: -1.8, shortName: "SNAP" },
226    { name: "Pinterest", parent: "Technology", value: 45, progress: -15.3, shortName: "PINS" },
227    { name: "Palantir", parent: "Technology", value: 40, progress: 2.9, shortName: "PLTR" },
228    { name: "ASML", parent: "Technology", value: 30, progress: 3.5, shortName: "ASML" },
229    { name: "ARM", parent: "Technology", value: 25, progress: 5.2, shortName: "ARM" },
230    { name: "ServiceNow", parent: "Technology", value: 20, progress: 11.8, shortName: "NOW" },
231    { name: "Atlassian", parent: "Technology", value: 18, progress: 7.9, shortName: "TEAM" },
232    { name: "Twilio", parent: "Technology", value: 16, progress: -17.2, shortName: "TWLO" },
233    { name: "Cloudflare", parent: "Technology", value: 14, progress: 8.5, shortName: "NET" },
234    { name: "Snowflake", parent: "Technology", value: 12, progress: 2.7, shortName: "SNO" },
235    { name: "Okta", parent: "Technology", value: 10, progress: 11.4, shortName: "OKT" },
236    { name: "Shopify", parent: "Technology", value: 9, progress: 10.8, shortName: "SHO" },
237    { name: "Datadog", parent: "Technology", value: 8, progress: -12.1, shortName: "DDO" },
238    { name: "GitLab", parent: "Technology", value: 7, progress: -5.6, shortName: "GTLB" },
239    { name: "ZoomInfo", parent: "Technology", value: 6, progress: -0.8, shortName: "ZI" },
240    { name: "Elastic", parent: "Technology", value: 5, progress: 4.2, shortName: "EST" },
241    { name: "Wix", parent: "Technology", value: 4, progress: 0.9, shortName: "WIX" },
242    { name: "Fiverr", parent: "Technology", value: 3, progress: -2.5, shortName: "FVR" },
243];
244
245// This shows you how to use one of D3's broad layout strategies with the Performance of SciChart
246// using a local file as "d3-hierarchy.js" from this folder (no need to install from npm another dependency)
247// function prepareDataUsingD3Local(data: TTreemapDataItem[]): RectangluarNode[] {
248//     const root = d3.stratify()
249//         .id((d: TTreemapDataItem) => d.name)
250//         .parentId((d: TTreemapDataItem) => d.parent)(data);
251
252//     root.sum((d: TTreemapDataItem) => + d.value);
253
254//     d3.treemap()
255//         .size([WIDTH, HEIGHT])
256//         .padding(0.1)
257//         (root); // create the treemap layout
258
259//     return root.leaves() as RectangluarNode[];
260// }
261
262// uses NPM's "d3-hierarchy" package - recommended if you don't mind an extra 5kb dependency
263function prepareDataUsingD3External(data: TTreemapDataItem[]): RectangluarNode[] {
264    const root = stratify()
265        .id((d) => (d as TTreemapDataItem).name)
266        .parentId((d) => (d as TTreemapDataItem).parent)(data);
267
268    root.sum((d) => +(d as TTreemapDataItem).value);
269
270    treemap().size([WIDTH, HEIGHT]).padding(0.1)(root); // create the treemap layout
271
272    return root.leaves() as unknown as RectangluarNode[];
273}
274
275export async function drawExample(rootElement: string | HTMLDivElement) {
276    // Initialize SciChartSurface. Don't forget to await!
277    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
278        theme: appTheme.SciChartJsTheme,
279    });
280
281    // Create XAxis / YAxis
282    const xAxis = new NumericAxis(wasmContext, {
283        axisTitle: "X Axis",
284        isVisible: false,
285    });
286    sciChartSurface.xAxes.add(xAxis);
287
288    const yAxis = new NumericAxis(wasmContext, {
289        axisTitle: "Y Axis",
290        isVisible: false,
291        flippedCoordinates: true,
292    });
293    sciChartSurface.yAxes.add(yAxis);
294
295    const treemapData = prepareDataUsingD3External(RAW_DATA);
296    // const treemapData = prepareDataUsingD3External(RAW_DATA); // use this if you don't mind a 5kb dependency -> ("d3-hierarchy")
297
298    // Draw the Rectangle Series
299    const rectangleSeries = new FastRectangleRenderableSeries(wasmContext, {
300        dataSeries: new XyxyDataSeries(wasmContext, {
301            xValues: treemapData.map((d) => d.x0),
302            yValues: treemapData.map((d) => d.y0),
303            x1Values: treemapData.map((d) => d.x1),
304            y1Values: treemapData.map((d) => d.y1),
305            metadata: treemapData.map((d) => d.data) as any[],
306        }),
307        columnXMode: EColumnMode.StartEnd,
308        columnYMode: EColumnYMode.TopBottom,
309        strokeThickness: 2,
310        resamplingMode: EResamplingMode.None,
311        dataLabelProvider: new TreemapDataLabelProvider({
312            skipMode: EDataLabelSkipMode.ShowAll,
313            color: "white",
314            style: {
315                fontSize: 13,
316                multiLineAlignment: EMultiLineAlignment.Center,
317                lineSpacing: 5,
318            },
319            horizontalTextPosition: EHorizontalTextPosition.Center,
320            verticalTextPosition: EVerticalTextPosition.Center,
321            metaDataSelector: (md: unknown) => {
322                return (md as TTreemapDataItem).name;
323            },
324        }),
325        // send min and max value percentages to the palette provider as 2 params
326        paletteProvider: new StockTreemapPaletteProvider({
327            minValue: Math.min(...treemapData.map((d) => (d.data as TTreemapDataItem).progress)),
328            maxValue: Math.max(...treemapData.map((d) => (d.data as TTreemapDataItem).progress)),
329        }),
330    });
331    sciChartSurface.renderableSeries.add(rectangleSeries);
332
333    sciChartSurface.chartModifiers.add(new MouseWheelZoomModifier(), new ZoomExtentsModifier(), new ZoomPanModifier());
334
335    return { sciChartSurface, wasmContext };
336}
337

TreeMap Chart - React

Overview

This React example creates a TreeMap Chart using SciChart.js, wrapped in the SciChartReact component. It visualizes company valuations with color-coded performance metrics.

Technical Implementation

The chart initializes via drawExample passed to initChart prop. It combines FastRectangleRenderableSeries with D3.js for hierarchical layout. The StockTreemapPaletteProvider implements color interpolation for gains/losses.

Features and Capabilities

Dynamic labels adapt to rectangle size using TreemapDataLabelProvider. The example includes React-specific lifecycle management through the SciChartReact wrapper component.

Integration and Best Practices

The implementation demonstrates React best practices with async chart initialization and CSS theming via className prop. For advanced use, see React Charts with SciChart.js.

react Chart Examples & Demos

See Also: Charts added in v4 (16 Demos)

React Histogram Chart | React Charts | SciChart.js Demo

React Histogram Chart

Create a React Histogram Chart with custom texture fills and patterns. Try the SciChartReact wrapper component for seamless React integration today.

React Gantt Chart | React Charts | SciChart.js Demo

React Gantt Chart Example

Build a React Gantt Chart with SciChart. View the demo for horizontal bars, rounded corners and data labels to show project timelines and task completion.

React Choropleth Map | React Charts | SciChart.js Demo

React Choropleth Map Example

Create a React Choropleth map, a type of thematic map where areas are shaded or patterned in proportion to the value of a variable being represented.

React Multi-Layer Map | React Charts | SciChart.js Demo

React Multi-Layer Map Example

Create a React Multi-Layer Map Example, using FastTriangleRenderableSeries with GeoJSON data-points using a constrained delaunay triangulation algorithm.

React Animated Bar Chart | React Charts | SciChart.js Demo

React Animated Bar Chart Example

Bring annual comparison data to life with the React Animated Bar Chart example from SciChart. This demo showcases top 10 tennis players from 1990 to 2024.

React Vector Field Plot | React Charts | SciChart.js Demo

React Vector Field Plot

View the React Vector Field Plot example from SciChart, including dynamic vector generation, gradient-colored segments, and interactive zoom/pan. Try demo.

React Waterfall Chart | Bridge Chart | SciChart.js Demo

React Waterfall Chart | Bridge Chart

Build a React Waterfall Chart with dynamic coloring, multi-line data labels and responsive design, using the SciChartReact component for seamless integration.

React Box Plot Chart | React Charts | SciChart.js Demo

React Box Plot Chart

Try the React Box Plot Chart example for React-friendly chart lifecycle management, dynamic sub-surface positioning, and custom styling. Try the demo now.

React Triangle Series | Triangle Mesh Chart | SciChart.js

React Triangle Series | Triangle Mesh Chart

Create React Triangle Meshes with the Triangle Series from SciChart. This demo supports strip mode, list mode and the drawing of polygons. View the example.

NEW!
React Map Chart with Heatmap overlay | SciChart.js Demo

React Map Chart with Heatmap overlay

Design a highly dynamic React Map Chart with Heatmap overlay with SciChart's feature-rich JavaScript Chart Library. Get your free demo today.

Realtime Audio Analyzer Bars Demo | SciChart.js Demo

Realtime Audio Analyzer Bars Demo

Demonstrating the capability of SciChart.js to create a JavaScript Audio Analyzer Bars and visualize the Fourier-Transform of an audio waveform in realtime.

React Linear Gauges | React Charts | SciChart.js Demo

React Linear Gauges Example

View the React Linear Gauge Chart example to combine rectangles & annotations. Create a linear gauge dashboard with animated indicators and custom scales.

NEW!
React Order of Rendering | React Charts | SciChart.js Demo

React Order of Rendering Example

The React Order of Rendering example gives you full control of the draw order of series and annotations for charts. Try SciChart's advanced customizations.

Responsive HTML Annotations | React Charts | SciChart.js

React Responsive HTML Annotations Example

Build Responsive React HTML Annotations with SciChart. Use the advanced CSS container queries for responsive text layout and custom design. View demo now.

HTML Annotations and Custom in-chart Controls | SciChart

HTML Annotations and Custom in-chart Controls Example

React HTML Chart Control example demonstrates advanced HTML annotation integration and how to render HTML components within charts. Try the SciChart demo.

React Polar Modifiers | Polar Interactivity Modifiers

React Polar Modifiers | Polar Interactivity Modifiers Demo

Explore SciChart's Polar Interactivity Modifiers including zooming, panning, and cursor tracking. Try the demo to trial the Polar Chart Behavior Modifiers.

SciChart Ltd, 16 Beaufort Court, Admirals Way, Docklands, London, E14 9XL.