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 
src/drawExample.ts
import {
    HeatmapColorMap,
    HeatmapLegend,
    MouseWheelZoomModifier,
    NumericAxis,
    SciChartSurface,
    UniformHeatmapDataSeries,
    UniformHeatmapRenderableSeries,
    zeroArray2D,
    ZoomExtentsModifier,
    ZoomPanModifier,
} from "scichart";
import { appTheme, createChartTheme } from "./appTheme";

const MAX_SERIES = 100;
const WIDTH = 300;
const HEIGHT = 200;

// Draws a Heatmap chart in real-time
export const drawExample = async (rootElement: string | HTMLDivElement) => {
    // Create a SciChartSurface
    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
        theme: appTheme.SciChartJsTheme,
    });

    // Add XAxis and YAxis
    sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { isVisible: false }));
    sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { isVisible: false }));

    // Create a Heatmap Data-series. Pass heatValues as a number[][] to the UniformHeatmapDataSeries
    const initialZValues: number[][] = generateExampleData(WIDTH, HEIGHT, 200, 20, MAX_SERIES);
    const heatmapDataSeries = new UniformHeatmapDataSeries(wasmContext, {
        xStart: 0,
        xStep: 1,
        yStart: 0,
        yStep: 1,
        zValues: initialZValues,
    });

    // Create a Heatmap RenderableSeries with the color map. ColorMap.minimum/maximum defines the values in
    // HeatmapDataSeries which correspond to gradient stops at 0..1
    const heatmapSeries = new UniformHeatmapRenderableSeries(wasmContext, {
        dataSeries: heatmapDataSeries,
        useLinearTextureFiltering: false,
        colorMap: new HeatmapColorMap({
            minimum: 0,
            maximum: 200,
            gradientStops: [
                { offset: 1, color: appTheme.VividPink },
                { offset: 0.9, color: appTheme.VividOrange },
                { offset: 0.7, color: appTheme.MutedRed },
                { offset: 0.5, color: appTheme.VividGreen },
                { offset: 0.3, color: appTheme.VividSkyBlue },
                { offset: 0.2, color: appTheme.Indigo },
                { offset: 0, color: appTheme.DarkIndigo },
            ],
        }),
    });

    // Add heatmap to the chart
    sciChartSurface.renderableSeries.add(heatmapSeries);

    // Add interaction
    sciChartSurface.chartModifiers.add(new ZoomPanModifier({ enableZoom: true }));
    sciChartSurface.chartModifiers.add(new ZoomExtentsModifier());
    sciChartSurface.chartModifiers.add(new MouseWheelZoomModifier());

    // Functions for running the example in real-time
    let timerId: NodeJS.Timeout;
    let updateIndex: number = 0;

    const updateChart = () => {
        // Cycle through pre-generated data on timer tick
        const newZValues = generateExampleData(WIDTH, HEIGHT, 200, updateIndex++, MAX_SERIES);
        // Update the heatmap z-values
        heatmapDataSeries.setZValues(newZValues);
        if (updateIndex >= MAX_SERIES) {
            updateIndex = 0;
        }
        timerId = setTimeout(updateChart, 16);
    };

    const startUpdate = () => {
        if (!timerId) {
            updateChart();
        }
    };

    const stopUpdate = () => {
        clearTimeout(timerId);
        timerId = undefined;
    };

    const subscribeToRenderStats = (callback: (stats: { xSize: number; ySize: number; fps: number }) => void) => {
        // Handle drawing/updating FPS
        let lastRendered = Date.now();
        sciChartSurface.rendered.subscribe(() => {
            const currentTime = Date.now();
            const timeDiffSeconds = (currentTime - lastRendered) / 1000;
            lastRendered = currentTime;
            const fps = 1 / timeDiffSeconds;
            callback({
                xSize: heatmapDataSeries.arrayWidth,
                ySize: heatmapDataSeries.arrayHeight,
                fps,
            });
        });
    };

    return { sciChartSurface, subscribeToRenderStats, controls: { startUpdate, stopUpdate } };
};

// Draws a Heatmap legend over the <div id={divHeatmapLegend}></div>
export const drawHeatmapLegend = async (rootElement: string | HTMLDivElement) => {
    const { heatmapLegend, wasmContext } = await HeatmapLegend.create(rootElement, {
        theme: createChartTheme({
            sciChartBackground: appTheme.DarkIndigo + "BB",
            loadingAnimationBackground: appTheme.DarkIndigo + "BB",
        }),
        yAxisOptions: {
            isInnerAxis: true,
            labelStyle: {
                fontSize: 12,
                color: appTheme.ForegroundColor,
            },
            axisBorder: {
                borderRight: 1,
                color: appTheme.ForegroundColor + "77",
            },
            majorTickLineStyle: {
                color: appTheme.ForegroundColor,
                tickSize: 6,
                strokeThickness: 1,
            },
            minorTickLineStyle: {
                color: appTheme.ForegroundColor,
                tickSize: 3,
                strokeThickness: 1,
            },
        },
        colorMap: {
            minimum: 0,
            maximum: 200,
            gradientStops: [
                { offset: 1, color: appTheme.VividPink },
                { offset: 0.9, color: appTheme.VividOrange },
                { offset: 0.7, color: appTheme.MutedRed },
                { offset: 0.5, color: appTheme.VividGreen },
                { offset: 0.3, color: appTheme.VividSkyBlue },
                { offset: 0.2, color: appTheme.Indigo },
                { offset: 0, color: appTheme.DarkIndigo },
            ],
        },
    });

    return { sciChartSurface: heatmapLegend.innerSciChartSurface.sciChartSurface };
};

// This function generates data for the heatmap series example
// because data-generation is not trivial, we generate once before the example starts
// so you can see the speed & power of SciChart.js
function generateExampleData(
    width: number,
    height: number,
    cpMax: number,
    index: number,
    maxIndex: number
): number[][] {
    // Returns a 2-dimensional javascript array [height (y)] [width (x)] size
    const zValues = zeroArray2D([height, width]);

    // math.round but to X digits
    function roundTo(number: number, digits: number) {
        return number;
        // return parseFloat(number.toFixed(digits));
    }

    const angle = roundTo(Math.PI * 2 * index, 3) / maxIndex;

    // When appending data to a 2D Array for the heatmap, the order of appending (X,Y) does not matter
    // but when accessing the zValues[][] array, we set data [y] then [x]
    for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
            const v =
                (1 + roundTo(Math.sin(x * 0.04 + angle), 3)) * 50 +
                (1 + roundTo(Math.sin(y * 0.1 + angle), 3)) * 50 * (1 + roundTo(Math.sin(angle * 2), 3));
            const cx = width / 2;
            const cy = height / 2;
            const r = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy));
            const exp = Math.max(0, 1 - r * 0.008);
            const zValue = v * exp + Math.random() * 10;
            zValues[y][x] = zValue > cpMax ? cpMax : zValue;
        }
    }
    return zValues;
}

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 shared CSS controls 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.