Using Series Selection

Demonstrates how to add Series Selection to a chart using SciChart.js, High Performance JavaScript Charts

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

import {
    ECoordinateMode,
    EHorizontalAnchorPoint,
    IRenderableSeries,
    NumericAxis,
    NumberRange,
    SciChartSurface,
    SplineLineRenderableSeries,
    TextAnnotation,
    XyDataSeries,
    SeriesSelectionModifier,
    AUTO_COLOR,
    LegendModifier,
    GenericAnimation,
    EllipsePointMarker,
} from "scichart";

// Generate some data for the example
const dataSize = 30;
const xValues: number[] = [];
const yValues: number[] = [];
const y1Values: number[] = [];
const y2Values: number[] = [];
const y3Values: number[] = [];
for (let i = 0; i < dataSize; i++) {
    xValues.push(i);
    y3Values.push(Math.random() + 1);
    y2Values.push(Math.random() + 1.8);
    y1Values.push(Math.random() + 2.5);
    yValues.push(Math.random() + 3.6);
}

// Custom function called when series is hovered
const onHoveredChanged = (sourceSeries: IRenderableSeries, isHovered: boolean) => {
    console.log(`Series ${sourceSeries.dataSeries.dataSeriesName} isHovered=${isHovered}`);
    const targetSeriesOpacity = 1;
    const otherSeriesOpacity = isHovered ? 0.3 : 1;

    const sciChartSurface = sourceSeries.parentSurface;
    const otherSeries = sciChartSurface.renderableSeries.asArray().filter((rs) => rs !== sourceSeries);

    // Animate the hovered series and dim the remaining series.
    sciChartSurface.addAnimation(
        new GenericAnimation({
            from: sourceSeries.opacity,
            to: targetSeriesOpacity,
            duration: 100,
            onAnimate: (from, to, progress) => {
                const opacity = (to - from) * progress + from;
                sourceSeries.opacity = opacity;
                sourceSeries.pointMarker.opacity = opacity;
            },
        })
    );
    // Dim opacity on the other non-hovered series
    sciChartSurface.addAnimation(
        new GenericAnimation({
            from: otherSeries[0].opacity,
            to: otherSeriesOpacity,
            duration: 100,
            onAnimate: (from, to, progress) => {
                const opacity = (to - from) * progress + from;
                otherSeries.forEach((rs) => {
                    rs.opacity = opacity;
                    rs.pointMarker.opacity = opacity;
                });
            },
        })
    );
};

// Custom function called when a series is selected or deselected
const onSelectedChanged = (sourceSeries: IRenderableSeries, isSelected: boolean) => {
    console.log(`Series ${sourceSeries.dataSeries.dataSeriesName} isSelected=${isSelected}`);

    // Highlight selection with the theme foreground; deselection restores the series color.
    const targetSeriesStroke = isSelected ? appTheme.ForegroundColor : sourceSeries.pointMarker.fill;
    sourceSeries.stroke = targetSeriesStroke;
    sourceSeries.pointMarker.stroke = targetSeriesStroke;
};

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

    sciChartSurface.xAxes.add(new NumericAxis(wasmContext));
    sciChartSurface.yAxes.add(
        new NumericAxis(wasmContext, {
            growBy: new NumberRange(0.1, 0.1),
        })
    );

    sciChartSurface.chartModifiers.add(
        new SeriesSelectionModifier({
            enableHover: true,
            enableSelection: true,
        })
    );

    for (const { values, dataSeriesName } of [
        { values: yValues, dataSeriesName: "First Series" },
        { values: y1Values, dataSeriesName: "Second Series" },
        { values: y2Values, dataSeriesName: "Third Series" },
        { values: y3Values, dataSeriesName: "Fourth Series" },
    ]) {
        sciChartSurface.renderableSeries.add(
            new SplineLineRenderableSeries(wasmContext, {
                dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: values, dataSeriesName }),
                pointMarker: new EllipsePointMarker(wasmContext, {
                    fill: AUTO_COLOR,
                    stroke: AUTO_COLOR,
                    strokeThickness: 3,
                    width: 20,
                    height: 20,
                }),
                strokeThickness: 3,
                onHoveredChanged,
                onSelectedChanged,
            })
        );
    }

    // Add title annotation
    sciChartSurface.annotations.add(
        new TextAnnotation({
            text: "Hover, Click & Select to animate style!",
            fontSize: 20,
            textColor: appTheme.ForegroundColor,
            x1: 0.5,
            y1: 0,
            opacity: 0.77,
            horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
            xCoordinateMode: ECoordinateMode.Relative,
            yCoordinateMode: ECoordinateMode.Relative,
        })
    );

    // Add a legend to the chart
    sciChartSurface.chartModifiers.add(new LegendModifier({ margin: 25 }));

    return { sciChartSurface, wasmContext };
};

Chart Series Selection/Hover in React

Overview

This example demonstrates how to implement Series Selection in a SciChart.js chart within a React application. It showcases interactive features where users can hover over and select chart series, triggering animations and visual style changes in real-time.

Technical Implementation

Leveraging the React framework, the chart is initialized using the SciChartReact component. A dedicated draw function sets up the SciChartSurface with a SeriesSelectionModifier, numeric X and Y axes and adds multiple spline line series, each equipped with custom event callbacks for hover (onHoveredChanged) and selection (onSelectedChanged) events. These event callbacks use the GenericAnimation API to smoothly animate opacity transitions and update visual properties such as stroke and point markers. Annotations and legends are also incorporated to provide context and enhance user interaction, as detailed in the SciChart.js Series Selection Documentation.

Features and Capabilities

This example highlights several key features including real-time hover effects, series selection modifications, and animated transitions. When a series is hovered, it smoothly transitions to full opacity while the others are dimmed. Selecting a series updates its visual style to distinguish it further, ensuring clear feedback for user interactions. The chart also includes text annotations and an integrated legend to improve usability and data interpretation.

Integration and Best Practices

By utilizing the modular nature of React, the example cleanly separates chart initialization from the component structure, following best practices for performance and maintainability. The use of event callbacks for dynamic style updates and the implementation of smooth animations with GenericAnimation are excellent examples of optimizing interactive charting in a React environment. Developers seeking further guidance on integrating SciChart.js with React may also refer to the React integration best practices for more detailed insights.