Chart Axis Image labels

Demonstrates how to use Images as Labels using SciChart.js, High Performance JavaScript Charts

src/drawExample.ts
import {
    XyDataSeries,
    TTextStyle,
    NumericAxis,
    FastColumnRenderableSeries,
    SciChartSurface,
    TextureManager,
    EAutoRange,
    ENumericFormat,
    createImagesArrayAsync,
    EFillPaletteMode,
    EStrokePaletteMode,
    IFillPaletteProvider,
    IStrokePaletteProvider,
    parseColorToUIntArgb,
    IRenderableSeries,
    IPointMetadata,
    PaletteFactory,
    GradientParams,
    Point,
    WaveAnimation,
    NumberRange,
    TextAnnotation,
    EHorizontalAnchorPoint,
    ECoordinateMode,
} from "scichart";
import { appTheme } from "./appTheme";

export const drawExample = (emojiUrls: string[]) => async (rootElement: string | HTMLDivElement) => {
    // Dataset = 'percentage market share of phones, 2022'
    const dataset = [
        { name: "Apple", percent: 28.41 },
        { name: "Samsung", percent: 28.21 },
        { name: "Xiaomi", percent: 12.73 },
        { name: "Huawei", percent: 5.27 },
        { name: "Oppo", percent: 5.53 },
        { name: "Vivo", percent: 4.31 },
        { name: "Realme", percent: 3.16 },
        { name: "Motorola", percent: 2.33 },
        { name: "Unknown", percent: 2.19 },
        { name: "LG", percent: 0.85 },
        { name: "OnePlus", percent: 1.11 },
        { name: "Tecno", percent: 1.09 },
        { name: "Infinix", percent: 0.96 },
        { name: "Google", percent: 0.77 },
        { name: "Nokia", percent: 0.45 },
    ];
    // Create the SciChartSurface with theme
    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
        theme: appTheme.SciChartJsTheme,
    });

    const xAxis = new NumericAxis(wasmContext, {
        // Ensure there can be 1 label per item in the dataset.
        // Also see major/minor delta in the docs
        maxAutoTicks: 15,
        axisTitle: "Mobile phone manufacturer",
        growBy: new NumberRange(0.02, 0.02),
        // required for image labels
        useNativeText: false,
    });
    // We need the data value as plain text
    xAxis.labelProvider.numericFormat = ENumericFormat.NoFormat;

    // SciChart utility function to create HtmlImage elements from urls
    const emojies = await createImagesArrayAsync(emojiUrls);

    // Override labelProvider.getLabelTexture() to return animage
    const getLabelTexture = (labelText: string, textureManager: TextureManager, labelStyle: TTextStyle) => {
        const index = parseInt(labelText);
        if (!isNaN(index)) {
            const emoji = emojies[index];
            if (emoji) {
                return textureManager.createTextureFromImage(emoji, 40, 40);
            }
        }
        return textureManager.createTextTexture([labelText], labelStyle);
    };
    xAxis.labelProvider.getLabelTexture = getLabelTexture;

    // Disable shared cache for this provider, otherwise other axes might pick up the emoji textures
    xAxis.labelProvider.useSharedCache = false;

    sciChartSurface.xAxes.add(xAxis);

    // Create a Y-Axis with standard properties
    sciChartSurface.yAxes.add(
        new NumericAxis(wasmContext, {
            autoRange: EAutoRange.Always,
            axisTitle: "Market Share (%)",
            growBy: new NumberRange(0, 0.1),
            labelPostfix: " %",
        })
    );

    // Add a column series.
    sciChartSurface.renderableSeries.add(
        new FastColumnRenderableSeries(wasmContext, {
            // Name index to xvalue for category axis
            // Map percentage to yvalue
            // store the manufacturer name in the metadata (used to generate colors)
            dataSeries: new XyDataSeries(wasmContext, {
                xValues: dataset.map((row, index) => index),
                yValues: dataset.map((row) => row.percent),
            }),
            strokeThickness: 0,
            // // Optional datalabels on series. To enable set a style and position
            // dataLabels: {
            //     horizontalTextPosition: EHorizontalTextPosition.Center,
            //     verticalTextPosition: EVerticalTextPosition.Top,
            //     style: { fontFamily: "Arial", fontSize: 16, padding: new Thickness(0,0,20,0) },
            //     color: appTheme.ForegroundColor,
            // },
            // each column occupies 50% of available space
            dataPointWidth: 0.5,
            // add a gradient fill in X (why not?)
            paletteProvider: PaletteFactory.createGradient(
                wasmContext,
                new GradientParams(new Point(0, 0), new Point(1, 1), [
                    { offset: 0, color: appTheme.VividPink },
                    { offset: 0.2, color: appTheme.VividOrange },
                    { offset: 0.3, color: appTheme.MutedRed },
                    { offset: 0.5, color: appTheme.VividGreen },
                    { offset: 0.7, color: appTheme.VividSkyBlue },
                    { offset: 0.9, color: appTheme.Indigo },
                    { offset: 1, color: appTheme.DarkIndigo },
                ]),
                { enableFill: true, enableStroke: true }
            ),
            // Bit more eye candy ;)
            animation: new WaveAnimation({ duration: 1000 }),
        })
    );

    // Add title annotation
    sciChartSurface.annotations.add(
        new TextAnnotation({
            text: "Mobile Phone manufacturer market share (2022)",
            fontSize: 20,
            textColor: appTheme.ForegroundColor,
            x1: 0.5,
            y1: 0,
            opacity: 0.77,
            horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
            xCoordinateMode: ECoordinateMode.Relative,
            yCoordinateMode: ECoordinateMode.Relative,
        })
    );

    sciChartSurface.zoomExtents();
    return { sciChartSurface, wasmContext };
};

export class EmojiPaletteProvider implements IStrokePaletteProvider, IFillPaletteProvider {
    public readonly strokePaletteMode = EStrokePaletteMode.SOLID;
    public readonly fillPaletteMode = EFillPaletteMode.SOLID;
    private readonly pfYellow = parseColorToUIntArgb("FFCC4D");
    private readonly pfBlue = parseColorToUIntArgb("5DADEC");
    private readonly pfOrange = parseColorToUIntArgb("F58E01");
    private readonly pfRed = parseColorToUIntArgb("DE2A43");
    private readonly pfPink = parseColorToUIntArgb("FE7891");

    // tslint:disable-next-line:no-empty
    public onAttached(parentSeries: IRenderableSeries): void {}

    // tslint:disable-next-line:no-empty
    public onDetached(): void {}

    public overrideFillArgb(xValue: number, yValue: number, index: number): number {
        if (xValue === 0 || xValue === 4 || xValue === 8) {
            return this.pfYellow;
        } else if (xValue === 1 || xValue === 7) {
            return this.pfBlue;
        } else if (xValue === 2 || xValue === 5) {
            return this.pfOrange;
        } else if (xValue === 3 || xValue === 6) {
            return this.pfRed;
        } else if (xValue === 9) {
            return this.pfPink;
        } else {
            return undefined;
        }
    }

    public overrideStrokeArgb(
        xValue: number,
        yValue: number,
        index: number,
        opacity?: number,
        metadata?: IPointMetadata
    ): number {
        return undefined;
    }
}

Image Labels on Axis Example - JavaScript

Overview

This example demonstrates how to integrate SciChart.js using JavaScript to create a high-performance column chart with custom image labels replacing traditional text labels on the X-axis. The chart visualizes mobile phone market share data by mapping numeric indices to asynchronously loaded images, creating an engaging and visually appealing representation.

Technical Implementation

The chart initialization is performed procedurally by creating a SciChartSurface with a images instead of axis labels, as described in the Image Labels Documentation. A numeric X-axis is configured using the NumericAxis and its label provider is customized by overriding the LabelProvider.getLabelTexture and LabelProvider.getLabelTextureAsync methods. This customization leverages the asynchronous helper function createImagesArrayAsync to load images efficiently and use the TextureManager for dynamic texture creation. Furthermore, a gradient fill is applied to the column series using the PaletteFactory, which enhances visual transitions and overall aesthetics.

Features and Capabilities

Key features include the real-time animation of the column series using WaveAnimation and the implementation of custom palette providers for dynamic gradient colors. The asynchronous image loading and deferred texture creation optimize performance, ensuring that the chart runs smoothly even with multiple custom label textures.

Integration and Best Practices

This example follows best practices for JavaScript chart integration by using a procedural, step-by-step initialization approach instead of relying on framework-specific hooks or the Builder API. Developers benefit from explicit control over chart customization, as each component—from the axis configuration to the advanced label rendering—is directly managed. For further details on custom label rendering and performance optimization, consult the Image Labels Documentation and review the Performance Tips & Tricks in the SciChart.js documentation.