Data Labels

Shows how you can add Data Labels to a chart using SciChart.js

Fullscreen

Edit

 Edit

Docs

drawExample.ts

index.html

vanilla.ts

ExampleDataProvider.ts

theme.ts

Copy to clipboard
Minimise
Fullscreen
1import { appTheme } from "../../../theme";
2import { ExampleDataProvider } from "../../../ExampleData/ExampleDataProvider";
3
4import {
5    DataLabelProvider,
6    EllipsePointMarker,
7    ENumericFormat,
8    EVerticalTextPosition,
9    EWrapTo,
10    EXyDirection,
11    FastColumnRenderableSeries,
12    FastLineRenderableSeries,
13    formatNumber,
14    IPointMetadata,
15    MouseWheelZoomModifier,
16    NativeTextAnnotation,
17    NumberRange,
18    NumericAxis,
19    parseColorToUIntArgb,
20    SciChartSurface,
21    SplineLineRenderableSeries,
22    Thickness,
23    XyDataSeries,
24    ZoomExtentsModifier,
25    ZoomPanModifier,
26} from "scichart";
27
28export const drawExample = async (rootElement: string | HTMLDivElement) => {
29    // Create a SciChartSurface
30    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
31        theme: appTheme.SciChartJsTheme,
32    });
33
34    // Add an X, Y Axis
35    sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { visibleRangeLimit: new NumberRange(0, 20) }));
36    sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { growBy: new NumberRange(0.05, 0.05) }));
37
38    // normal labels
39    const data1 = ExampleDataProvider.getSpectrumData(0, 20, 5, 1, 0.01);
40    const colSeries = new FastColumnRenderableSeries(wasmContext, {
41        dataSeries: new XyDataSeries(wasmContext, data1),
42        fill: appTheme.VividOrange + "33",
43        stroke: appTheme.VividOrange,
44        dataPointWidth: 0.7,
45        strokeThickness: 1,
46        dataLabels: {
47            // To enable datalabels, set fontFamily and size
48            style: { fontFamily: "Arial", fontSize: 16, padding: new Thickness(5, 0, 5, 0) },
49            color: appTheme.VividOrange,
50            // Normal label format and precision options are supported
51            precision: 2,
52        },
53    });
54    const highCol = parseColorToUIntArgb(appTheme.VividGreen);
55    const lowCol = parseColorToUIntArgb(appTheme.VividOrange);
56    (colSeries.dataLabelProvider as DataLabelProvider).getColor = (state, text) => {
57        if (state.yVal() > 0) return highCol;
58        else return lowCol;
59    };
60    sciChartSurface.renderableSeries.add(colSeries);
61
62    const labels = ["Data", "Labels", "can", "come", "from", "values", "in", "metadata"];
63    sciChartSurface.renderableSeries.add(
64        new SplineLineRenderableSeries(wasmContext, {
65            dataSeries: new XyDataSeries(wasmContext, {
66                xValues: data1.xValues,
67                yValues: data1.yValues.map((y) => y * 0.8 + 4),
68                metadata: data1.xValues.map(
69                    (x, i) => ({ isSelected: false, text: labels[(i - 1) / 2] } as IPointMetadata)
70                ),
71            }),
72            stroke: appTheme.VividSkyBlue,
73            strokeThickness: 3,
74            pointMarker: new EllipsePointMarker(wasmContext, {
75                width: 7,
76                height: 7,
77                fill: appTheme.ForegroundColor,
78                strokeThickness: 0,
79            }),
80            dataLabels: {
81                style: { fontFamily: "Arial", fontSize: 16 },
82                color: appTheme.ForegroundColor,
83                // @ts-ignore
84                metaDataSelector: (md) => md.text,
85            },
86        })
87    );
88
89    sciChartSurface.annotations.add(
90        new NativeTextAnnotation({
91            x1: 1,
92            y1: 10,
93            text: "Series with 1000 points, using custom getText function to only show labels for peaks, with x and y",
94            textColor: appTheme.VividGreen,
95            wrapTo: EWrapTo.ViewRect,
96        })
97    );
98
99    // Custom getText
100    const data2 = ExampleDataProvider.getSpectrumData(10, 1000, 10, 100, 0.02);
101    const series = new FastLineRenderableSeries(wasmContext, {
102        dataSeries: new XyDataSeries(wasmContext, {
103            xValues: data2.xValues.map((x) => x / 50),
104            yValues: data2.yValues.map((y) => y * 0.3 + 8),
105        }),
106        stroke: appTheme.VividGreen,
107        strokeThickness: 3,
108        dataLabels: {
109            style: { fontFamily: "Arial", fontSize: 14, padding: new Thickness(0, 0, 3, 0) },
110            color: appTheme.ForegroundColor,
111            aboveBelow: false,
112            verticalTextPosition: EVerticalTextPosition.Above,
113        },
114    });
115    (series.dataLabelProvider as DataLabelProvider).getText = (state) => {
116        const i = state.index;
117        if (
118            i > state.indexStart &&
119            i < state.indexEnd &&
120            state.yVal() > state.yVal(i - 1) &&
121            state.yVal() > state.yVal(i + 1)
122        ) {
123            return `X: ${formatNumber(state.xVal(), ENumericFormat.Decimal, 2)}\nY: ${formatNumber(
124                state.yVal(),
125                ENumericFormat.Decimal,
126                3
127            )}`;
128        }
129        return undefined;
130    };
131    sciChartSurface.renderableSeries.add(series);
132
133    sciChartSurface.annotations.add(
134        new NativeTextAnnotation({
135            x1: 1,
136            y1: 14,
137            text: "Series with 200 points. Using pointGapThreshold = 1 to show labels when zoomed in enough for there to be space for them",
138            textColor: appTheme.VividPink,
139            wrapTo: EWrapTo.ViewRect,
140        })
141    );
142    // Show labels when zoomed in
143    const data3 = ExampleDataProvider.getSpectrumData(0, 200, 10, 20, 0.02);
144    sciChartSurface.renderableSeries.add(
145        new FastLineRenderableSeries(wasmContext, {
146            dataSeries: new XyDataSeries(wasmContext, {
147                xValues: data3.xValues.map((x) => x / 10),
148                yValues: data3.yValues.map((y) => y * 0.3 + 12),
149            }),
150            stroke: appTheme.VividPink,
151            strokeThickness: 3,
152            dataLabels: {
153                style: { fontFamily: "Arial", fontSize: 12 },
154                color: appTheme.ForegroundColor,
155                pointGapThreshold: 1,
156            },
157        })
158    );
159
160    // Optional: Add some interactivity modifiers
161    sciChartSurface.chartModifiers.add(new ZoomPanModifier({ enableZoom: true }));
162    sciChartSurface.chartModifiers.add(new ZoomExtentsModifier());
163    sciChartSurface.chartModifiers.add(new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }));
164
165    sciChartSurface.zoomExtents();
166
167    return { sciChartSurface, wasmContext };
168};
169

Data Labels - JavaScript

Overview

This example demonstrates advanced customization of data labels in a SciChart.js chart using JavaScript. The implementation sets up a SciChartSurface with numeric axes and multiple renderable series to showcase how dynamic label styling and metadata-driven text labels can enhance data visualization.

Technical Implementation

The chart is constructed by first creating a SciChartSurface and adding numeric X and Y axes. Three renderable series are configured: a column series with dynamic label colors using a custom function in the DataLabelProvider, a spline series that extracts label text from metadata via a custom metaDataSelector (see Getting Labels from Metadata), and a line series that conditionally displays labels only at peak values using a customized getText function as detailed in Custom DataLabel Formatting with getText(). Interactive modifiers such as ZoomPanModifier, ZoomExtentsModifier, and MouseWheelZoomModifier are incorporated to enable smooth zooming and panning, which can be explored further in Adding Zooming, Panning Behavior.

Features and Capabilities

The example illustrates several advanced features including conditional label styling based on data values, metadata-driven labels, and performance optimizations achieved by showing labels only when there is sufficient space. In addition, custom point markers like EllipsePointMarker are used to clearly highlight data points. Dynamic color styling is applied using the parseColorToUIntArgb() function, aligning with techniques described in Data Label Colouring.

Integration and Best Practices

This implementation adheres to best practices in resource management by encapsulating chart creation within an asynchronous function that returns a cleanup mechanism for disposing of the SciChartSurface. Developers leveraging JavaScript can refer to the Getting Started with SciChart JS guide to understand proper initialization and disposal of chart resources. The example’s modular approach ensures that chart configuration remains maintainable and scalable while enabling advanced interactive visualization through integrated chart modifiers.

javascript Chart Examples & Demos

See Also: Styling and Theming (11 Demos)

Chart Background Image with Transparency | SciChart.js

Chart Background Image with Transparency

Demonstrates how to create a JavaScript Chart with background image using transparency in SciChart.js

Styling a JavaScript Chart in Code | SciChart.js Demo

Styling a JavaScript Chart in Code

Demonstrates how to style a JavaScript Chart entirely in code with SciChart.js themeing API

Using Theme Manager in JavaScript Chart | SciChart.js

Using Theme Manager in JavaScript Chart

Demonstrates our Light and Dark Themes for JavaScript Charts with SciChart.js ThemeManager API

Create a Custom Theme for JavaScript Chart | SciChart.js

Create a Custom Theme for JavaScript Chart

Demonstrates how to create a Custom Theme for a SciChart.js JavaScript Chart using our Theming API

Coloring Series per-point using the PaletteProvider

Coloring Series per-point using the PaletteProvider

Demonstrates per-point coloring in JavaScript chart types with SciChart.js PaletteProvider API

JavaScript Point-Markers Chart | Javascript Charts | SciChart.js

JavaScript Point-Markers Chart

Demonstrates the different point-marker types for JavaScript Scatter charts (Square, Circle, Triangle and Custom image point-marker)

Dashed Line Styling | Javascript Charts | SciChart.js Demo

Dashed Line Styling

Demonstrates dashed line series in JavaScript Charts with SciChart.js

JavaScript Chart with Multi-Style Series | SciChart.js

JavaScript Chart with Multi-Style Series

Demonstrates how to apply multiple different styles to a single series using RenderDataTransform

JavaScript Chart with lines split by thresholds | SciChart

JavaScript Chart with lines split by thresholds

Demonstrates how to use a RenderDataTransform to split lines into multiple segments so they can be individually colored according to thresholds

JavaScript Chart Title | Javascript Charts | SciChart.js Demo

JavaScript Chart Title

Demonstrates chart title with different position and alignment options

NEW!
JavaScript Order of Rendering | Javascript Charts | SciChart.js

JavaScript Order of Rendering Example

The JavaScript Order of Rendering example gives you full control of the draw order of series and annotations for charts. Try SciChart's advanced customizations.

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