JavaScript 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    EPointMarkerType,
12    AUTO_COLOR,
13    TextAnnotation,
14    EHorizontalAnchorPoint,
15    ECoordinateMode,
16    LegendModifier,
17    LineSeriesDataLabelProvider,
18    DataLabelState,
19    ELegendPlacement,
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: {
79                type: EPointMarkerType.Ellipse,
80                options: { fill: AUTO_COLOR, stroke: AUTO_COLOR, strokeThickness: 3, width: 20, height: 20 },
81            },
82            strokeThickness: 3,
83            // Optional visual feedback for selected points can be provided by the DataPointSelectionPaletteProvider
84            // When dataSeries.metadata[i].isSelected, this still is applied
85            paletteProvider: new DataPointSelectionPaletteProvider({ stroke, fill }),
86            // Optional: show datalabels but only for selected points
87            dataLabelProvider: getDataLabelProvider(),
88        })
89    );
90
91    sciChartSurface.renderableSeries.add(
92        new SplineLineRenderableSeries(wasmContext, {
93            id: "Series2",
94            dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: y1Values, dataSeriesName: "Second Series" }),
95            pointMarker: {
96                type: EPointMarkerType.Ellipse,
97                options: { fill: AUTO_COLOR, stroke: AUTO_COLOR, strokeThickness: 3, width: 20, height: 20 },
98            },
99            strokeThickness: 3,
100            // Optional visual feedback for selected points
101            paletteProvider: new DataPointSelectionPaletteProvider({ stroke, fill }),
102            // Optional: show datalabels but only for selected points
103            dataLabelProvider: getDataLabelProvider(),
104        })
105    );
106
107    sciChartSurface.renderableSeries.add(
108        new SplineLineRenderableSeries(wasmContext, {
109            id: "Series3",
110            dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: y2Values, dataSeriesName: "Third Series" }),
111            pointMarker: {
112                type: EPointMarkerType.Ellipse,
113                options: { fill: AUTO_COLOR, stroke: AUTO_COLOR, strokeThickness: 3, width: 20, height: 20 },
114            },
115            strokeThickness: 3,
116            // Optional visual feedback for selected points
117            paletteProvider: new DataPointSelectionPaletteProvider({ stroke, fill }),
118            // Optional: show datalabels but only for selected points
119            dataLabelProvider: getDataLabelProvider(),
120        })
121    );
122
123    sciChartSurface.renderableSeries.add(
124        new SplineLineRenderableSeries(wasmContext, {
125            id: "Series4",
126            dataSeries: new XyDataSeries(wasmContext, { xValues, yValues: y3Values, dataSeriesName: "Fourth Series" }),
127            pointMarker: {
128                type: EPointMarkerType.Ellipse,
129                options: { fill: AUTO_COLOR, stroke: AUTO_COLOR, strokeThickness: 3, width: 20, height: 20 },
130            },
131            strokeThickness: 3,
132            // Optional visual feedback for selected points
133            paletteProvider: new DataPointSelectionPaletteProvider({ stroke, fill }),
134            // Optional: show datalabels but only for selected points
135            dataLabelProvider: getDataLabelProvider(),
136        })
137    );
138
139    // Todo: Show how to programmatically set points. Requires some changes in scichart.js API
140
141    // Add title annotations
142    sciChartSurface.annotations.add(
143        new TextAnnotation({
144            text: "Click & Drag Select points",
145            fontSize: 20,
146            textColor: appTheme.ForegroundColor,
147            x1: 0.5,
148            opacity: 0.77,
149            horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
150            xCoordinateMode: ECoordinateMode.Relative,
151            yCoordinateMode: ECoordinateMode.Relative,
152        })
153    );
154
155    sciChartSurface.annotations.add(
156        new TextAnnotation({
157            text: "Try single click, CTRL+CLICK & Drag to select",
158            fontSize: 16,
159            textColor: appTheme.ForegroundColor,
160            x1: 0.5,
161            yCoordShift: 40,
162            opacity: 0.77,
163            horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
164            xCoordinateMode: ECoordinateMode.Relative,
165            yCoordinateMode: ECoordinateMode.Relative,
166        })
167    );
168
169    // Add a legend to the chart
170    sciChartSurface.chartModifiers.add(new LegendModifier({ placement: ELegendPlacement.BottomLeft }));
171
172    // Add the DataPointSelectonModifier to the chart.
173    // selectionChanged event / callback has the selected points in the arguments
174    const dataPointSelection = new DataPointSelectionModifier();
175    dataPointSelection.selectionChanged.subscribe((data: DataPointSelectionChangedArgs) => {
176        // When points are selected, set them - we render the selected points to a table below the chart
177        setSelectedPoints(data.selectedDataPoints);
178    });
179    sciChartSurface.chartModifiers.add(dataPointSelection);
180
181    return { wasmContext, sciChartSurface };
182};
183

Datapoint Selection – JavaScript

Overview

This example demonstrates how to implement data point selection in SciChart.js Charts using JavaScript. The example creates several spline line series with simulated data and enables interactive selection of data points. It leverages the SciChart.js core components such as axes, renderable series, annotations, and modifiers to provide a rich, interactive charting experience.

Technical Implementation

The chart is set up by creating a SciChartSurface with a WebAssembly context (see Creating a new SciChartSurface and loading Wasm for more details). Two numeric axes are added to the surface and a number of spline line renderable series are created using an XyDataSeries. Each series uses custom point markers styled according to an automatic color scheme. In addition, a custom data label provider built with the LineSeriesDataLabelProvider is implemented to conditionally display labels only for selected points based on metadata. For handling data point selection, the DataPointSelectionModifier is added to the chart. Its event subscription mechanism is used to update a table of selected points via a callback when selection changes occur. The example also makes use of the DataPointSelectionPaletteProvider to customize the stroke and fill of selected data points denoted by metadata.isSelected.

Features and Capabilities

This chart supports interactive selection via click, CTRL+CLICK, and click & drag actions. Selected data points display custom data labels that include the x and y values, and are visually distinguished by a custom palette. The example also includes text annotations (configured with TextAnnotation) to guide the user, and a legend provided by the LegendModifier to give context to the rendered series. Overall, the example illustrates how multiple renderable series can be enhanced with conditional data labels, palette customization, and interactive selection behavior.

Integration and Best Practices

Even though this example is implemented in JavaScript, it demonstrates several best practices applicable across different frameworks. It uses the native event subscription model provided by SciChart.js modifiers (see Common ChartModifiers Features) and leverages the high-performance WebAssembly context for rendering. Developers can use these techniques to efficiently manage real-time interactions and achieve optimal performance when handling multiple series and complex user interactions. Overall, the implementation provides a solid foundation that can be extended or integrated into larger applications.

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