JavaScript Chart with Vertically Stacked Axes

Vertically-Stacked Axis in SciChart.js allows several traces with independent Y-axis to be placed on the same chart, stacking the Y-Axis and enabling an ECG/EEG-style trace. Great for neurological apps, medical apps, earthquake monitoring.

src/drawExample.ts
import { appTheme } from "./appTheme";

import { EWrapTo, NativeTextAnnotation, TSciChart } from "scichart";

import {
    EAxisAlignment,
    ECoordinateMode,
    EExecuteOn,
    EHorizontalAnchorPoint,
    EXyDirection,
    FastLineRenderableSeries,
    LeftAlignedOuterVerticallyStackedAxisLayoutStrategy,
    MouseWheelZoomModifier,
    NumberRange,
    NumericAxis,
    RubberBandXyZoomModifier,
    SciChartSurface,
    XAxisDragModifier,
    XyDataSeries,
    YAxisDragModifier,
    ZoomExtentsModifier,
} from "scichart";

export const drawExample = async (rootElement: string | HTMLDivElement) => {
    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
        theme: appTheme.SciChartJsTheme,
    });

    sciChartSurface.layoutManager.leftOuterAxesLayoutStrategy =
        new LeftAlignedOuterVerticallyStackedAxisLayoutStrategy();

    sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "X Axis" }));

    // Add title annotation
    sciChartSurface.annotations.add(
        new NativeTextAnnotation({
            text: "Vertically Stacked Axis: Custom layout of axis to allow traces to overlap. Useful for ECG charts",
            fontSize: 16,
            textColor: appTheme.ForegroundColor,
            x1: 0.5,
            y1: 0,
            opacity: 0.77,
            horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
            xCoordinateMode: ECoordinateMode.Relative,
            yCoordinateMode: ECoordinateMode.Relative,
            wrapTo: EWrapTo.ViewRect,
        })
    );

    const seriesCount: number = 10;
    for (let i = 0; i < seriesCount; i++) {
        const range = 10 / seriesCount;
        const yAxis = new NumericAxis(wasmContext, {
            id: "Y" + i,
            visibleRange: new NumberRange(-range, range),
            axisAlignment: EAxisAlignment.Left,
            zoomExtentsToInitialRange: true,
            maxAutoTicks: 5,
            drawMinorGridLines: false,
            axisBorder: { borderTop: 5, borderBottom: 5 },
            axisTitle: `Y ${i}`,
        });
        sciChartSurface.yAxes.add(yAxis);

        const lineSeries = new FastLineRenderableSeries(wasmContext, {
            yAxisId: yAxis.id,
            stroke: "auto",
            strokeThickness: 2,
        });
        lineSeries.dataSeries = getRandomSinewave(wasmContext, 0, Math.random() * 3, Math.random() * 50, 10000, 10);
        sciChartSurface.renderableSeries.add(lineSeries);
    }

    // Optional: Add some interactivity modifiers to enable zooming and panning
    sciChartSurface.chartModifiers.add(
        new YAxisDragModifier(),
        new XAxisDragModifier(),
        new RubberBandXyZoomModifier({
            xyDirection: EXyDirection.XDirection,
            executeCondition: { button: EExecuteOn.MouseRightButton },
        }),
        new MouseWheelZoomModifier({ xyDirection: EXyDirection.YDirection }),
        new ZoomExtentsModifier()
    );

    return { sciChartSurface, wasmContext };
};

function getRandomSinewave(
    wasmContext: TSciChart,
    pad: number,
    amplitude: number,
    phase: number,
    pointCount: number,
    freq: number
) {
    const dataSeries = new XyDataSeries(wasmContext);

    for (let i = 0; i < pad; i++) {
        const time = (10 * i) / pointCount;
        dataSeries.append(time, 0);
    }

    for (let i = pad, j = 0; i < pointCount; i++, j++) {
        amplitude = Math.min(3, Math.max(0.1, amplitude * (1 + (Math.random() - 0.5) / 10)));
        freq = Math.min(50, Math.max(0.1, freq * (1 + (Math.random() - 0.5) / 50)));

        const time = (10 * i) / pointCount;
        const wn = (2 * Math.PI) / (pointCount / freq);

        const d = amplitude * Math.sin(j * wn + phase);
        dataSeries.append(time, d);
    }

    return dataSeries;
}

Vertically Stacked Axes Example with JavaScript

Overview

This example demonstrates how to create a high-performance chart using SciChart.js with JavaScript. It showcases a custom setup where multiple independent Y-axes are vertically stacked to allow overlapping data traces similar to ECG/EEG visualizations. The chart is initialized asynchronously and leverages native JavaScript for a straightforward integration in web applications.

Technical Implementation

The chart is created by calling SciChartSurface.create() asynchronously, ensuring that the WebAssembly context is fully loaded before rendering. A custom axis layout is implemented using the LeftAlignedOuterVerticallyStackedAxisLayoutStrategy as described in the Vertically Stacked Axis Layout documentation. Each data series is associated with its own Y-axis, configured with a specific visible range and border styling. Data for each series is generated dynamically using a sine wave algorithm via the XyDataSeries, which aligns with best practices as shown in the Tutorial on Adding Series and Data. In addition, multiple interactive modifiers such as YAxisDragModifier, XAxisDragModifier, RubberBandXyZoomModifier, and MouseWheelZoomModifier are added to enhance user interactivity.

Features and Capabilities

The example emphasizes several advanced features:

  • Multiple Y-Axes: Each data trace is plotted against its own Y-axis, enabling a stacked layout that is ideal for overlapping visualizations.
  • High-Performance Rendering: The use of FastLineRenderableSeries ensures smooth rendering of large data sets. More details can be found in the FastLineRenderableSeries API Documentation.
  • Interactive Modifiers: Advanced interactivity is provided through drag and zoom modifiers, allowing dynamic exploration of the chart.
  • Annotations: A text annotation is incorporated using NativeTextAnnotation to offer contextual information directly on the chart.

Integration and Best Practices

This implementation is a prime example of integrating SciChart.js with JavaScript. Developers can follow the asynchronous initialization pattern and proper lifecycle management evidenced by the cleanup function which calls sciChartSurface.delete(). For more information on JavaScript integration, refer to the Getting Started with SciChart JS guide. Additionally, proper memory management and disposal practices are covered in the Deleting DataSeries Memory documentation. By adopting these techniques, developers can ensure optimal performance and maintainability in their web applications.