React Heatmap Chart

If you want to learn about heatmaps. this demo shows you how to create a React Heatmap Chart using SciChart.js, our 5-star rated JavaScript Chart Component.

# Heatmap Size: 0 x 0
FPS: 00

Fullscreen

Edit

 Edit

Docs

drawExample.ts

index.tsx

theme.ts

Copy to clipboard
Minimise
Fullscreen
1import {
2    HeatmapColorMap,
3    HeatmapLegend,
4    MouseWheelZoomModifier,
5    NumericAxis,
6    SciChartSurface,
7    UniformHeatmapDataSeries,
8    UniformHeatmapRenderableSeries,
9    zeroArray2D,
10    ZoomExtentsModifier,
11    ZoomPanModifier,
12} from "scichart";
13import { appTheme } from "../../../theme";
14
15const MAX_SERIES = 100;
16const WIDTH = 300;
17const HEIGHT = 200;
18
19// Draws a Heatmap chart in real-time
20export const drawExample = async (rootElement: string | HTMLDivElement) => {
21    // Create a SciChartSurface
22    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
23        theme: appTheme.SciChartJsTheme,
24    });
25
26    // Add XAxis and YAxis
27    sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { isVisible: false }));
28    sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { isVisible: false }));
29
30    // Create a Heatmap Data-series. Pass heatValues as a number[][] to the UniformHeatmapDataSeries
31    const initialZValues: number[][] = generateExampleData(WIDTH, HEIGHT, 200, 20, MAX_SERIES);
32    const heatmapDataSeries = new UniformHeatmapDataSeries(wasmContext, {
33        xStart: 0,
34        xStep: 1,
35        yStart: 0,
36        yStep: 1,
37        zValues: initialZValues,
38    });
39
40    // Create a Heatmap RenderableSeries with the color map. ColorMap.minimum/maximum defines the values in
41    // HeatmapDataSeries which correspond to gradient stops at 0..1
42    const heatmapSeries = new UniformHeatmapRenderableSeries(wasmContext, {
43        dataSeries: heatmapDataSeries,
44        useLinearTextureFiltering: false,
45        colorMap: new HeatmapColorMap({
46            minimum: 0,
47            maximum: 200,
48            gradientStops: [
49                { offset: 1, color: appTheme.VividPink },
50                { offset: 0.9, color: appTheme.VividOrange },
51                { offset: 0.7, color: appTheme.MutedRed },
52                { offset: 0.5, color: appTheme.VividGreen },
53                { offset: 0.3, color: appTheme.VividSkyBlue },
54                { offset: 0.2, color: appTheme.Indigo },
55                { offset: 0, color: appTheme.DarkIndigo },
56            ],
57        }),
58    });
59
60    // Add heatmap to the chart
61    sciChartSurface.renderableSeries.add(heatmapSeries);
62
63    // Add interaction
64    sciChartSurface.chartModifiers.add(new ZoomPanModifier({ enableZoom: true }));
65    sciChartSurface.chartModifiers.add(new ZoomExtentsModifier());
66    sciChartSurface.chartModifiers.add(new MouseWheelZoomModifier());
67
68    // Functions for running the example in real-time
69    let timerId: NodeJS.Timeout;
70    let updateIndex: number = 0;
71
72    const updateChart = () => {
73        // Cycle through pre-generated data on timer tick
74        const newZValues = generateExampleData(WIDTH, HEIGHT, 200, updateIndex++, MAX_SERIES);
75        // Update the heatmap z-values
76        heatmapDataSeries.setZValues(newZValues);
77        if (updateIndex >= MAX_SERIES) {
78            updateIndex = 0;
79        }
80        timerId = setTimeout(updateChart, 16);
81    };
82
83    const startUpdate = () => {
84        if (!timerId) {
85            updateChart();
86        }
87    };
88
89    const stopUpdate = () => {
90        clearTimeout(timerId);
91        timerId = undefined;
92    };
93
94    const subscribeToRenderStats = (callback: (stats: { xSize: number; ySize: number; fps: number }) => void) => {
95        // Handle drawing/updating FPS
96        let lastRendered = Date.now();
97        sciChartSurface.rendered.subscribe(() => {
98            const currentTime = Date.now();
99            const timeDiffSeconds = (currentTime - lastRendered) / 1000;
100            lastRendered = currentTime;
101            const fps = 1 / timeDiffSeconds;
102            callback({
103                xSize: heatmapDataSeries.arrayWidth,
104                ySize: heatmapDataSeries.arrayHeight,
105                fps,
106            });
107        });
108    };
109
110    return { sciChartSurface, subscribeToRenderStats, controls: { startUpdate, stopUpdate } };
111};
112
113// Draws a Heatmap legend over the <div id={divHeatmapLegend}></div>
114export const drawHeatmapLegend = async (rootElement: string | HTMLDivElement) => {
115    const { heatmapLegend, wasmContext } = await HeatmapLegend.create(rootElement, {
116        theme: {
117            ...appTheme.SciChartJsTheme,
118            sciChartBackground: appTheme.DarkIndigo + "BB",
119            loadingAnimationBackground: appTheme.DarkIndigo + "BB",
120        },
121        yAxisOptions: {
122            isInnerAxis: true,
123            labelStyle: {
124                fontSize: 12,
125                color: appTheme.ForegroundColor,
126            },
127            axisBorder: {
128                borderRight: 1,
129                color: appTheme.ForegroundColor + "77",
130            },
131            majorTickLineStyle: {
132                color: appTheme.ForegroundColor,
133                tickSize: 6,
134                strokeThickness: 1,
135            },
136            minorTickLineStyle: {
137                color: appTheme.ForegroundColor,
138                tickSize: 3,
139                strokeThickness: 1,
140            },
141        },
142        colorMap: {
143            minimum: 0,
144            maximum: 200,
145            gradientStops: [
146                { offset: 1, color: appTheme.VividPink },
147                { offset: 0.9, color: appTheme.VividOrange },
148                { offset: 0.7, color: appTheme.MutedRed },
149                { offset: 0.5, color: appTheme.VividGreen },
150                { offset: 0.3, color: appTheme.VividSkyBlue },
151                { offset: 0.2, color: appTheme.Indigo },
152                { offset: 0, color: appTheme.DarkIndigo },
153            ],
154        },
155    });
156
157    return { sciChartSurface: heatmapLegend.innerSciChartSurface.sciChartSurface };
158};
159
160// This function generates data for the heatmap series example
161// because data-generation is not trivial, we generate once before the example starts
162// so you can see the speed & power of SciChart.js
163function generateExampleData(
164    width: number,
165    height: number,
166    cpMax: number,
167    index: number,
168    maxIndex: number
169): number[][] {
170    // Returns a 2-dimensional javascript array [height (y)] [width (x)] size
171    const zValues = zeroArray2D([height, width]);
172
173    // math.round but to X digits
174    function roundTo(number: number, digits: number) {
175        return number;
176        // return parseFloat(number.toFixed(digits));
177    }
178
179    const angle = roundTo(Math.PI * 2 * index, 3) / maxIndex;
180
181    // When appending data to a 2D Array for the heatmap, the order of appending (X,Y) does not matter
182    // but when accessing the zValues[][] array, we set data [y] then [x]
183    for (let y = 0; y < height; y++) {
184        for (let x = 0; x < width; x++) {
185            const v =
186                (1 + roundTo(Math.sin(x * 0.04 + angle), 3)) * 50 +
187                (1 + roundTo(Math.sin(y * 0.1 + angle), 3)) * 50 * (1 + roundTo(Math.sin(angle * 2), 3));
188            const cx = width / 2;
189            const cy = height / 2;
190            const r = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy));
191            const exp = Math.max(0, 1 - r * 0.008);
192            const zValue = v * exp + Math.random() * 10;
193            zValues[y][x] = zValue > cpMax ? cpMax : zValue;
194        }
195    }
196    return zValues;
197}
198

Heatmap Chart Example in React

Overview

This example demonstrates a real-time updating Heatmap Chart built using SciChart.js and integrated into a React application. The implementation leverages the SciChart React component for chart creation and lifecycle management, providing a high-performance chart that displays dynamic heatmap data with an accompanying legend.

Technical Implementation

The chart is initialized using the <SciChartReact/> component which receives custom draw functions via the onInit callback. This function sets up the chart with numerical axes, a uniform heatmap data series, and various chart modifiers for interactive features such as zoom and pan. Real-time updates are managed via a timed loop mechanism (using setTimeout) that refreshes the heatmap’s data series while a subscription to render events tracks FPS and data dimensions. Developers interested in understanding effective real-time update strategies can explore the Realtime Heatmap Documentation documentation.

Features and Capabilities

The implementation offers several advanced features and customizations including real-time data streaming, dynamic performance monitoring, and interactive chart modifiers (like zoom pan and mouse wheel zoom). The detailed color map and data generation function ensure that the heatmap accurately represents complex data with continuous visual transitions. These capabilities are essential for applications requiring high-performance data visualization.

Integration and Best Practices

The React integration demonstrates best practices such as using the useRef hook to manage chart control functions and handling chart initialization and cleanup within the component lifecycle. The example also incorporates Material UI components to build an interactive toolbar, providing users with clear control over starting and stopping the real-time updates. For further guidance on integrating SciChart.js within a React framework, developers can refer to the React Charts with SciChart.js: Introducing “SciChart React” article and the Tutorial 01 - Setting up a project with scichart-react and config object documentation.

react Chart Examples & Demos

See Also: JavaScript Chart Types (39 Demos)

React Line Chart | React Charts | SciChart.js Demo

React Line Chart

Discover how to create a high performance React Line Chart with SciChart - the leading JavaScript library. Get your free demo now.

React Spline Line Chart | React Charts | SciChart.js Demo

React Spline Line Chart

Discover how to create a React Spline Line Chart with SciChart. Demo includes algorithm for smoother lines. Get your free trial now.

React Digital Line Chart | React Charts | SciChart.js Demo

React Digital Line Chart

Discover how to create a React Digital Line Chart with SciChart - your feature-rich JavaScript Chart Library. Get your free demo now.

React Band Chart | React Charts | SciChart.js Demo

React Band Chart

Easily create a React Band Chart or High-Low Fill with SciChart - high performance JavaScript Chart Library. Get your free trial now.

React Spline Band Chart | React Charts | SciChart.js Demo

React Spline Band Chart

SciChart's React Spline Band Chart makes it easy to draw thresholds or fills between two lines on a chart. Get your free demo today.

React Digital Band Chart | React Charts | SciChart.js Demo

React Digital Band Chart

Learn how to create a React Digital Band Chart or High-Low Fill Chart with SciChart's easy-to-follow demos. Get your free trial today.

React Bubble Chart | Online JavaScript Chart Examples

React Bubble Chart

Create a high performance React Bubble Chart with Sci-Chart. Demo shows how to draw point-markers at X,Y locations. Get your free demo now.

React Candlestick Chart | Online JavaScript Chart Examples

React Candlestick Chart

Discover how to create a React Candlestick Chart or Stock Chart using SciChart.js. For high Performance JavaScript Charts, get your free demo now.

React Column Chart | React Charts | SciChart.js Demo

React Column Chart

React Column Chart demo by SciChart supports gradient fill and paletteproviders for more custom coloring options. Get your free demo now.

React Population Pyramid | React Charts | SciChart.js Demo

React Population Pyramid

Population Pyramid of Europe and Africa

React Error Bars Char | React Charts | SciChart.js Demo

React Error Bars Chart

Create React Error Bars Chart using high performance SciChart.js. Display uncertainty or statistical confidence of a data-point. Get free demo now.

React Impulse Chart | React Charts | SciChart.js Demo

React Impulse Chart

Easily create React Impulse Chart or Stem Chart using SciChart.js - our own high performance JavaScript Chart Library. Get your free trial now.

React Text Chart | React Charts | SciChart.js Demo

React Text Chart

Create React Text Chart with high performance SciChart.js.

React Fan Chart | React Charts | SciChart.js Demo

React Fan Chart

Discover how to create React Fan Chart with SciChart. Zoom in to see the detail you can go to using our JavaScript Charts. Get your free demo today.

React Non Uniform Heatmap Chart | React Charts | SciChart.js

React Non Uniform Heatmap Chart

Create React Non Uniform Chart using high performance SciChart.js. Display Heatmap with variable cell sizes. Get free demo now.

React Heatmap Chart With Contours | SciChart.js Demo

React Heatmap Chart With Contours Example

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

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.

React Mountain Chart | React Charts | SciChart.js Demo

React Mountain Chart

Create React Mountain Chart with SciChart.js. Zero line can be zero or a specific value. Fill color can be solid or gradient as well. Get a free demo now.

React Spline Mountain Chart | React Charts | SciChart.js

React Spline Mountain Chart

React Spline Mountain Chart design made easy. Use SciChart.js' JavaScript Charts for high performance, feature-rich designs. Get free demo now.

React Digital Mountain Chart | React Charts | SciChart.js

React Digital Mountain Chart

Create React Digital Mountain Chart with a stepped-line visual effect. Get your free trial of SciChart's 5-star rated JavaScript Chart Component now.

React Realtime Mountain Chart | View Online At SciChart

React Realtime Mountain Chart

React Realtime Mountain Chart made easy. Add animated, real-time updates with SciChart.js - high performance JavaScript Charts. Get free trial now.

React Scatter Chart | React Charts | SciChart.js Demo

React Scatter Chart

Create React Scatter Chart with high performance SciChart.js. Easily render pre-defined point types. Supports custom shapes. Get your free trial now.

React Stacked Column Chart | Online JavaScript Charts

React Stacked Column Chart

Discover how to create a React Stacked Column Chart using our feature-rich JavaScript Chart Library, SciChart.js. Get your free demo today!

React Stacked Group Column Chart | View Examples Now

React Stacked Column Side by Side

Design React Stacked Group Column Chart side-by-side using our 5-star rated JavaScript Chart Framework, SciChart.js. Get your free demo now.

React Stacked Mountain Chart | React Charts | SciChart.js

React Stacked Mountain Chart

Design a high performance React Stacked Mountain Chart with SciChart.js - your one-stop JavaScript chart library. Get free demo now to get started.

React Smooth Stacked Mountain Chart | SciChart.js Demo

React Smooth Stacked Mountain Chart

Design a high performance React Stacked Mountain Chart with SciChart.js - your one-stop JavaScript chart library. Get free demo now to get started.

React Pie Chart | React Charts | SciChart.js Demo

React Pie Chart

Easily create and customise a high performance React Pie Chart with 5-star rated SciChart.js. Get your free trial now to access the whole library.

React Donut Chart | React Charts | SciChart.js Demo

React Donut Chart

Create React Donut Chart with 5-star rated SciChart.js chart library. Supports legends, text labels, animated updates and more. Get free trial now.

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.

React Quadrant Chart using Background Annotations | SciChart

React Quadrant Chart using Background Annotations

Demonstrates how to color areas of the chart surface using background Annotations using SciChart.js Annotations API

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 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.

React Treemap Chart | React Charts | SciChart.js Demo

React Treemap Chart

Create a React Treemap Chart to define rectangle positions based on total value. Use SciChart FastRectangleRenderableSeries and d3-hierarchy.js layouts.

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