React Chart Data Point Selection

Demonstrates how to Select Data Points on a chart using SciChart.js, High Performance JavaScript Charts

Selected Points

Series Name
X Value
Y Value

Fullscreen

Edit

 Edit

Docs

drawExample.ts

index.tsx

containerSizeHooks.ts

theme.ts

Copy to clipboard
Minimise
Fullscreen
1import {
2    SciChartSurface,
3    NumericAxis,
4    NumberRange,
5    XyDataSeries,
6    DataPointSelectionModifier,
7    DataPointSelectionChangedArgs,
8    DataPointInfo,
9    DataPointSelectionPaletteProvider,
10    SplineLineRenderableSeries,
11    AUTO_COLOR,
12    TextAnnotation,
13    EHorizontalAnchorPoint,
14    ECoordinateMode,
15    LegendModifier,
16    LineSeriesDataLabelProvider,
17    DataLabelState,
18    ELegendPlacement,
19    EllipsePointMarker,
20} from "scichart";
21import { appTheme } from "../../../theme";
22
23// Generate some data for the example
24const dataSize = 30;
25const xValues: number[] = [];
26const yValues: number[] = [];
27const y1Values: number[] = [];
28const y2Values: number[] = [];
29const y3Values: number[] = [];
30const y4Values: number[] = [];
31for (let i = 0; i < dataSize; i++) {
32    xValues.push(i);
33    y4Values.push(Math.random());
34    y3Values.push(Math.random() + 1);
35    y2Values.push(Math.random() + 1.8);
36    y1Values.push(Math.random() + 2.5);
37    yValues.push(Math.random() + 3.6);
38}
39
40export const drawExample = async (
41    rootElement: string | HTMLDivElement,
42    setSelectedPoints: (selectedPoints: DataPointInfo[]) => void
43) => {
44    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
45        theme: appTheme.SciChartJsTheme,
46    });
47
48    sciChartSurface.xAxes.add(new NumericAxis(wasmContext));
49    sciChartSurface.yAxes.add(
50        new NumericAxis(wasmContext, {
51            growBy: new NumberRange(0.1, 0.1),
52        })
53    );
54
55    // Stroke/fill for selected points
56    const stroke = appTheme.ForegroundColor;
57    const fill: string = appTheme.PaleSkyBlue + "77";
58
59    // Optional: show datalabels but only for selected points
60    const getDataLabelProvider = () => {
61        const dataLabelProvider = new LineSeriesDataLabelProvider();
62        dataLabelProvider.style = { fontFamily: "Arial", fontSize: 13 };
63        dataLabelProvider.color = appTheme.ForegroundColor;
64        dataLabelProvider.getText = (state: DataLabelState) => {
65            return state.getMetaData()?.isSelected
66                ? `x,y [${state.xValues[state.index].toFixed(1)}, ` +
67                      `${state.yValues[state.index].toFixed(1)}] selected`
68                : "";
69        };
70        return dataLabelProvider;
71    };
72
73    // Add some series onto the chart for selection
74    sciChartSurface.renderableSeries.add(
75        new SplineLineRenderableSeries(wasmContext, {
76            id: "Series1",
77            dataSeries: new XyDataSeries(wasmContext, { xValues, yValues, dataSeriesName: "First Series" }),
78            pointMarker: new EllipsePointMarker(wasmContext, {
79                fill: AUTO_COLOR,
80                stroke: AUTO_COLOR,
81                strokeThickness: 3,
82                width: 20,
83                height: 20,
84            }),
85            strokeThickness: 3,
86            // Optional visual feedback for selected points can be provided by the DataPointSelectionPaletteProvider
87            // When dataSeries.metadata[i].isSelected, this still is applied
88            paletteProvider: new DataPointSelectionPaletteProvider({ stroke, fill }),
89            // Optional: show datalabels but only for selected points
90            dataLabelProvider: getDataLabelProvider(),
91        })
92    );
93
94    sciChartSurface.renderableSeries.add(
95        new SplineLineRenderableSeries(wasmContext, {
96            id: "Series2",
97            dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: y1Values, dataSeriesName: "Second Series" }),
98            pointMarker: new EllipsePointMarker(wasmContext, {
99                fill: AUTO_COLOR,
100                stroke: AUTO_COLOR,
101                strokeThickness: 3,
102                width: 20,
103                height: 20,
104            }),
105            strokeThickness: 3,
106            // Optional visual feedback for selected points
107            paletteProvider: new DataPointSelectionPaletteProvider({ stroke, fill }),
108            // Optional: show datalabels but only for selected points
109            dataLabelProvider: getDataLabelProvider(),
110        })
111    );
112
113    sciChartSurface.renderableSeries.add(
114        new SplineLineRenderableSeries(wasmContext, {
115            id: "Series3",
116            dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: y2Values, dataSeriesName: "Third Series" }),
117            pointMarker: new EllipsePointMarker(wasmContext, {
118                fill: AUTO_COLOR,
119                stroke: AUTO_COLOR,
120                strokeThickness: 3,
121                width: 20,
122                height: 20,
123            }),
124            strokeThickness: 3,
125            // Optional visual feedback for selected points
126            paletteProvider: new DataPointSelectionPaletteProvider({ stroke, fill }),
127            // Optional: show datalabels but only for selected points
128            dataLabelProvider: getDataLabelProvider(),
129        })
130    );
131
132    sciChartSurface.renderableSeries.add(
133        new SplineLineRenderableSeries(wasmContext, {
134            id: "Series4",
135            dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: y3Values, dataSeriesName: "Fourth Series" }),
136            pointMarker: new EllipsePointMarker(wasmContext, {
137                fill: AUTO_COLOR,
138                stroke: AUTO_COLOR,
139                strokeThickness: 3,
140                width: 20,
141                height: 20,
142            }),
143            strokeThickness: 3,
144            // Optional visual feedback for selected points
145            paletteProvider: new DataPointSelectionPaletteProvider({ stroke, fill }),
146            // Optional: show datalabels but only for selected points
147            dataLabelProvider: getDataLabelProvider(),
148        })
149    );
150
151    // Todo: Show how to programmatically set points. Requires some changes in scichart.js API
152
153    // Add title annotations
154    sciChartSurface.annotations.add(
155        new TextAnnotation({
156            text: "Click & Drag Select points",
157            fontSize: 20,
158            textColor: appTheme.ForegroundColor,
159            x1: 0.5,
160            opacity: 0.77,
161            horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
162            xCoordinateMode: ECoordinateMode.Relative,
163            yCoordinateMode: ECoordinateMode.Relative,
164        })
165    );
166
167    sciChartSurface.annotations.add(
168        new TextAnnotation({
169            text: "Try single click, CTRL+CLICK & Drag to select",
170            fontSize: 16,
171            textColor: appTheme.ForegroundColor,
172            x1: 0.5,
173            yCoordShift: 40,
174            opacity: 0.77,
175            horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
176            xCoordinateMode: ECoordinateMode.Relative,
177            yCoordinateMode: ECoordinateMode.Relative,
178        })
179    );
180
181    // Add a legend to the chart
182    sciChartSurface.chartModifiers.add(new LegendModifier({ placement: ELegendPlacement.BottomLeft }));
183
184    // Add the DataPointSelectonModifier to the chart.
185    // selectionChanged event / callback has the selected points in the arguments
186    const dataPointSelection = new DataPointSelectionModifier();
187    dataPointSelection.selectionChanged.subscribe((data: DataPointSelectionChangedArgs) => {
188        // When points are selected, set them - we render the selected points to a table below the chart
189        setSelectedPoints(data.selectedDataPoints);
190    });
191    sciChartSurface.chartModifiers.add(dataPointSelection);
192
193    return { wasmContext, sciChartSurface };
194};
195

React Chart Data Point Selection

Overview

This example demonstrates a React implementation of a high performance SciChart.js chart that enables interactive data point selection. The chart renders multiple spline line series with customizable point markers and annotations. Users can select individual or multiple data points and see real-time updates reflected in a separate list rendered alongside the chart. For futher details please see the DataPoint Selection Documentation.

Technical Implementation

The chart is initialized using the <SciChartReact/> component, which is integrated into the React framework via an initChart callback. This callback, defined in the drawExample.ts file, sets up numeric axes, multiple SplineLineRenderableSeries, and customizes data point appearance using the DataPointSelectionPaletteProvider. To capture user interactions, the example adds a DataPointSelectionModifier to the chart that triggers a selectionChanged event. This event is then synchronized with React state using the useState hook, ensuring that selected points are displayed timely. Developers can learn more about integrating SciChart.js with React in the Creating a SciChart React Component from the Ground Up guide as well as the React Charts with SciChart.js: Introducing “SciChart React” article.

Features and Capabilities

The core features of this example include interactive data point selection, customized palette styling for selected data points (denoted by metadata.isSelected), and dynamic annotations providing immediate feedback. The use of advanced series components like SplineLineRenderableSeries and point marker customization through EPointMarkerType enhances the chart's visual interactivity. For additional technical insights, the React Chart Data Point Selection - SciChart.js Demo offers a live example, and the DataPointSelectionModifier Documentation provides detailed API guidance.

Integration and Best Practices

Efficient React integration is achieved through the use of hooks such as useState and useRef, ensuring responsive layouts and optimal state management. The example demonstrates how to synchronize chart events with React state updates, enabling seamless user interactions and real-time data displays. This approach aligns with best practices for creating high-performance, interactive charts in React, as discussed in the React Charts with SciChart.js: Introducing “SciChart React” article. Moreover, the example highlights how to effectively manage component responsiveness and event handling, ensuring the chart adapts cleanly to various display sizes.

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