React Smooth Stacked Mountain Chart

Learn how to make a React Smooth Stacked Mountain Chart using with SciChart's powerful JavaScript Charts and it's range of features.

src/drawExample.ts
import {
    AUTO_COLOR,
    BaseDataSeries,
    ELegendOrientation,
    ELegendPlacement,
    LegendModifier,
    makeIncArray,
    MouseWheelZoomModifier,
    NumericAxis,
    ScaleAnimation,
    SciChartSurface,
    StackedMountainCollection,
    SmoothStackedMountainRenderableSeries,
    XyDataSeries,
    ZoomExtentsModifier,
    ZoomPanModifier,
} from "scichart";
import { appTheme } from "./appTheme";

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

    // Create an xAxis, yAxis
    sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { labelPrecision: 0 }));
    sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { labelPrecision: 0 }));

    // Group these StackedMountain series together in a StackedMountainCollection
    const stackedMountainCollection = new StackedMountainCollection(wasmContext);

    const xValues = makeIncArray(20);
    for (let i = 0; i < 10; i++) {
        const yValues = xValues.map(() => Math.random() * 10);
        const stackedMountain = new SmoothStackedMountainRenderableSeries(wasmContext, {
            id: i.toString(),
            dataSeries: new XyDataSeries(wasmContext, { xValues, yValues }),
            fill: AUTO_COLOR,
            stroke: AUTO_COLOR,
            strokeThickness: 2,
            // Stagger each series so the stack builds from bottom to top.
            animation: new ScaleAnimation({ duration: 500, delay: i * 200 }),
        });
        stackedMountainCollection.add(stackedMountain);
    }

    // Add the StackedMountainCollection to the chart
    sciChartSurface.renderableSeries.add(stackedMountainCollection);

    // Add some interactivity modifiers
    sciChartSurface.chartModifiers.add(
        new ZoomExtentsModifier(),
        new ZoomPanModifier({ enableZoom: true }),
        new MouseWheelZoomModifier()
    );

    const legendModifier = new LegendModifier({
        placement: ELegendPlacement.TopLeft,
        orientation: ELegendOrientation.Vertical,
        showLegend: true,
        showCheckboxes: true,
        showSeriesMarkers: true,
    });
    // Add a legend to the chart to show the series
    sciChartSurface.chartModifiers.add(legendModifier);

    stackedMountainCollection.asArray().forEach((series) =>
        series.isVisibleChanged.subscribe((data) => {
            if (data.isVisible) {
                data.sourceSeries.runAnimation(
                    new ScaleAnimation({
                        duration: 500,
                    })
                );
            } else {
                // To animate out, we have to trick the series into remaining visible while the animation runs.
                // We set the backing value of isVisible to true, and only set it false when the animation completes
                // @ts-ignore
                data.sourceSeries.isVisibleProperty = true;
                data.sourceSeries.runAnimation(
                    new ScaleAnimation({
                        duration: 500,
                        reverse: true,
                        onCompleted: () => {
                            (data.sourceSeries.dataSeries as BaseDataSeries).revertAnimationVectors();
                            // @ts-ignore
                            data.sourceSeries.isVisibleProperty = false;
                            // Force the legend to update
                            legendModifier.sciChartLegend.invalidateLegend();
                        },
                    })
                );
            }
        })
    );

    sciChartSurface.zoomExtents();

    const toggleHundredPercentMode = (value: boolean) => {
        stackedMountainCollection.isOneHundredPercent = value;
        sciChartSurface.zoomExtents(200);
    };

    return { sciChartSurface, controls: { toggleHundredPercentMode } };
};

React Smooth Stacked Mountain Chart

Overview

This example demonstrates the creation of a React Smooth Stacked Mountain Chart using SciChart.js. The chart is designed to showcase stacking multiple smooth mountain series with interactive features such as zooming, panning, and toggling between normal and 100% stacked modes. The example leverages React functional components, hooks, and shared CSS controls to provide a modern and responsive charting experience.

Technical Implementation

The chart is initialized asynchronously using the SciChart.js API within a React component. The core chart is built by creating a SciChartSurface that hosts the x and y axes. A StackedMountainCollection is used to group multiple SmoothStackedMountainRenderableSeries. Each series is fed with randomized data and animated using the ScaleAnimation for smooth transitions. Series visibility changes trigger subscription-based events that run animations before updating the series state. For more details on initializing the SciChartSurface asynchronously and integrating with React hooks, refer to the Creating a SciChart React Component from the Ground Up guide.

Features and Capabilities

This example highlights several advanced features and customizations including:

  • Real-time updates: Event subscriptions monitor visibility changes, triggering animations and ensuring smooth state transitions.
  • Interactive legend and tooltips: A legend modifier is added with customization options like checkboxes and series markers.
  • Dynamic mode switching: Users can toggle between standard stacked and 100% stacked modes via a shared CSS controls toggle button group. These capabilities provide insights into building interactive financial and scientific charts, similar to approaches discussed in React Charts with SciChart.js: Introducing “SciChart React”. A variation on the Stacked Mountain Series is the SmoothStackedMountainRenderableSeries..

Integration and Best Practices

The integration with React is achieved using the <SciChartReact/> component, which encapsulates the initialization logic of the SciChartSurface. React hooks such as useState and useRef are employed to manage state and communicate with child components. The use of shared CSS controls button group for mode switching showcases how to blend interactive UI elements with advanced chart configuration. Additionally, the animation framework provided by SciChart.js, exemplified by ScaleAnimation, ensures that series transitions are smooth and performant. Developers are encouraged to review performance optimization techniques, as outlined in various SciChart.js documentation pages, to further enhance real-time interactions, as seen on the React Charts with SciChart.js: Introducing “SciChart React” page.

By following these integration guidelines and embracing React best practices, developers can achieve efficient and highly interactive charting solutions with SciChart.js.