JavaScript Chart with Multi-Style Series

Demonstrates how to use multiple styles on a single series on JavaScript Charts using SciChart.js, High Performance JavaScript Charts. This uses a RenderDataTransform to split the data so that we can draw the selected points using additional customised drawingProviders. This means that modifiers still see a single series with the original data.

src/drawExample.ts
import {
    BaseRenderDataTransform,
    NumberRange,
    RenderPassData,
    IPointSeries,
    XyDataSeries,
    SciChartSurface,
    NumericAxis,
    TrianglePointMarker,
    EllipsePointMarker,
    PointMarkerDrawingProvider,
    IPointMarker,
    FastColumnRenderableSeries,
    GradientParams,
    Point,
    ColumnSeriesDrawingProvider,
    DataPointSelectionModifier,
    LineSeriesDrawingProvider,
    FastLineRenderableSeries,
    ILineSeriesDrawingProviderProperties,
    ELineDrawMode,
    OhlcPointSeriesResampled,
    IOhlcPointSeries,
    NativeTextAnnotation,
    ECoordinateMode,
    EHorizontalAnchorPoint,
    EVerticalAnchorPoint,
    vectorToArrayViewF64,
} from "scichart";
import { appTheme } from "./appTheme";

/**
 * This transform turns xy data into ohlc.  Unselected points are in y (close).
 * Selected points in low for pointmarkers, and selected plus points either side in high for lines.
 * If you only need this for points or columns, you could transform to Xyy instead
 */
class SplitRenderDataTransform extends BaseRenderDataTransform<OhlcPointSeriesResampled> {
    protected createPointSeries(): OhlcPointSeriesResampled {
        return new OhlcPointSeriesResampled(this.wasmContext, new NumberRange(0, 0));
    }
    protected runTransformInternal(renderPassData: RenderPassData): IPointSeries {
        const { xValues: oldX, yValues: oldY, indexes: oldI, resampled } = renderPassData.pointSeries;
        // this.pointSeries is the target.  Clear the existing values
        const { xValues, yValues, highValues, lowValues, indexes } = this.pointSeries;
        // Resampled buffers already cover the visible range; raw buffers need the index range.
        const iStart = resampled ? 0 : renderPassData.indexRange.min;
        const iEnd = resampled ? oldX.size() - 1 : renderPassData.indexRange?.max;
        const length = iEnd - iStart + 1;
        // Resize before creating array views: a later allocation would invalidate those views.
        xValues.resizeFast(length);
        yValues.resizeFast(length);
        highValues.resizeFast(length);
        lowValues.resizeFast(length);
        indexes.resizeFast(length);
        // Views provide fast access to the native source and target buffers.
        const oldXView = vectorToArrayViewF64(oldX, this.wasmContext);
        const oldYView = vectorToArrayViewF64(oldY, this.wasmContext);
        const oldIndexView = vectorToArrayViewF64(oldI, this.wasmContext);
        const xView = vectorToArrayViewF64(xValues, this.wasmContext);
        const yView = vectorToArrayViewF64(yValues, this.wasmContext);
        const highView = vectorToArrayViewF64(highValues, this.wasmContext);
        const lowView = vectorToArrayViewF64(lowValues, this.wasmContext);
        const indexView = vectorToArrayViewF64(indexes, this.wasmContext);

        const ds = this.parentSeries.dataSeries as XyDataSeries;
        let prevSelected = false;
        let iOut = 0;
        for (let i = iStart; i <= iEnd; i++) {
            const index = resampled ? oldIndexView[i] : i;
            const md = ds.getMetadataAt(index);
            xView[iOut] = oldXView[i];
            indexView[iOut] = oldIndexView[i];
            let nextSelected = false;
            if (i < iEnd) {
                const nextmd = ds.getMetadataAt(index + 1);
                nextSelected = nextmd.isSelected;
            }
            yView[iOut] = md.isSelected ? NaN : oldYView[i];
            // For pointmarkers we just need the point itself
            lowView[iOut] = md.isSelected ? oldYView[i] : NaN;
            // need points either side of the selected value for the line to draw.
            highView[iOut] = prevSelected || md.isSelected || nextSelected ? oldYView[i] : NaN;
            prevSelected = md.isSelected;
            iOut++;
        }
        return this.pointSeries;
    }
}

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

    // Create X,Y Axis
    sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { growBy: new NumberRange(0.05, 0.05) }));
    sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { growBy: new NumberRange(0, 0.05) }));

    // Column series with different gradient fill for selected columns
    const xValues = Array.from({ length: 20 }, (x, i) => i);
    const colyValues = xValues.map(() => 10 + Math.random() * 40);
    const colmetadata = xValues.map(() => ({
        isSelected: Math.random() < 0.3,
    }));
    const columnSeries = new FastColumnRenderableSeries(wasmContext, {
        fillLinearGradient: new GradientParams(new Point(0, 0), new Point(0, 1), [
            { color: appTheme.MutedRed, offset: 0 },
            { color: appTheme.MutedTeal, offset: 1 },
        ]),
        dataSeries: new XyDataSeries(wasmContext, {
            xValues,
            yValues: colyValues,
            metadata: colmetadata,
            containsNaN: true,
        }),
        stroke: "transparent",
    });
    // We cannot use a paletteProvider to change a gradient fill, so we have to use a second drawingProvider
    const selectedColDP = new ColumnSeriesDrawingProvider(
        wasmContext,
        columnSeries,
        // configure this to draw using the selected points
        (ps) => (ps as IOhlcPointSeries).lowValues
    );
    selectedColDP.getProperties = (parentSeries) => {
        const { stroke, strokeThickness, fill } = parentSeries;
        return {
            opacity: 1,
            // Opacity setting does not currently apply to the gradient colors, so we have to apply it individually
            fillLinearGradient: new GradientParams(new Point(0, 0), new Point(0, 1), [
                { color: appTheme.MutedRed + "88", offset: 0 },
                { color: appTheme.MutedSkyBlue + "88", offset: 1 },
            ]),
            stroke,
            strokeThickness,
            fill,
        };
    };
    columnSeries.drawingProviders.push(selectedColDP);
    columnSeries.renderDataTransform = new SplitRenderDataTransform(
        columnSeries,
        wasmContext,
        columnSeries.drawingProviders
    );
    sciChartSurface.renderableSeries.add(columnSeries);

    const lineyValues = xValues.map((x) => 30 + x + x * Math.random());
    const linemetadata = xValues.map(() => ({
        isSelected: Math.random() < 0.3,
    }));
    // Line series with different pointmarker and dashed line for selected sections
    const lineSeries = new FastLineRenderableSeries(wasmContext, {
        dataSeries: new XyDataSeries(wasmContext, {
            xValues,
            yValues: lineyValues,
            metadata: linemetadata,
            containsNaN: true,
        }),
        pointMarker: new EllipsePointMarker(wasmContext, {
            width: 14,
            height: 14,
            strokeThickness: 0,
            fill: appTheme.VividSkyBlue,
        }),
        stroke: appTheme.VividTeal,
        strokeThickness: 3,
        drawNaNAs: ELineDrawMode.DiscontinuousLine,
    });

    const trianglePM = new TrianglePointMarker(wasmContext, {
        width: 15,
        height: 15,
        strokeThickness: 0,
        fill: appTheme.VividOrange,
    });
    // Additional line drawing for selected segments
    const selectedLineDP = new LineSeriesDrawingProvider(
        wasmContext,
        lineSeries,
        (ps) => (ps as IOhlcPointSeries).highValues
    );
    // Make this drawingProvider use dashed lines
    selectedLineDP.getProperties = (parentSeries) => {
        const { stroke, strokeThickness, isDigitalLine, lineType, drawNaNAs } = parentSeries;
        return {
            stroke,
            strokeThickness,
            strokeDashArray: [3, 4],
            isDigitalLine,
            lineType,
            drawNaNAs,
            containsNaN: true,
        } as ILineSeriesDrawingProviderProperties;
    };
    // Add this as the first drawingProviders so it draws behind all pointmarkers
    lineSeries.drawingProviders.unshift(selectedLineDP);

    // Additional point drawing for selected points
    const triangleDP = new PointMarkerDrawingProvider(
        wasmContext,
        lineSeries,
        (ps) => (ps as IOhlcPointSeries).lowValues
    );
    triangleDP.getProperties = () => {
        return { pointMarker: trianglePM as IPointMarker };
    };
    lineSeries.drawingProviders.push(triangleDP);

    // Apply the transform to all the drawingProviders
    lineSeries.renderDataTransform = new SplitRenderDataTransform(lineSeries, wasmContext, lineSeries.drawingProviders);
    sciChartSurface.renderableSeries.add(lineSeries);

    sciChartSurface.annotations.add(
        new NativeTextAnnotation({
            xCoordinateMode: ECoordinateMode.Pixel,
            yCoordinateMode: ECoordinateMode.Pixel,
            x1: 20,
            y1: 20,
            horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
            verticalAnchorPoint: EVerticalAnchorPoint.Top,
            text: "Selected points are styled differently.  Click and drag to change the selection",
            textColor: appTheme.ForegroundColor,
            fontSize: 16,
            opacity: 0.77,
        })
    );

    // Optional: Add Interactivity Modifiers
    sciChartSurface.chartModifiers.add(
        new DataPointSelectionModifier({
            allowClickSelect: true,
            onSelectionChanged: () => {
                lineSeries.renderDataTransform.requiresTransform = true;
                columnSeries.renderDataTransform.requiresTransform = true;
            },
        })
    );

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

Multi-Style Series Example - JavaScript

Overview

This example demonstrates how to apply multiple visual styles to a single series in a SciChart.js chart using JavaScript. The primary goal is to render selected data points differently from unselected data by leveraging a custom render transform alongside multiple drawing providers. This approach ensures that all interactive modifiers perceive the data as one unified series while the display is conditionally tailored based on metadata.

Technical Implementation

The implementation centers around a custom RenderDataTransform, implemented in the SplitRenderDataTransform class, which processes XY data and converts it into an OHLC-like format. Here, each data point is checked for a metadata flag (i.e. whether isSelected is set) and then assigned to specific fields that control different drawing providers (ISeriesDrawingProvider). For example, a portion of the data is used to render columns with gradient fills, while another subset is used to draw a line series with differently styled point markers and dashed line segments. This technique of conditional data transformation ensures that even when the appearance changes, the underlying series remains intact. Developers interested in efficient data transformation techniques can explore the RenderDataTransform API for a deeper understanding.

Features and Capabilities

The example showcases several advanced features:

  • Custom Render Transforms: The SplitRenderDataTransform examines metadata to split the series data so that selected points appear with alternate styling. This mechanism is vital for achieving dynamic visual differentiation and is closely related to conditional rendering with metadata.
  • Multiple Drawing Providers: Different drawing providers are used to render various aspects of the series. For instance, a ColumnSeriesDrawingProvider handles gradient styling for column series while LineSeriesDrawingProvider and PointMarkerDrawingProvider manage dashed line segments and custom point markers respectively. More details on configuring drawing providers can be found in the BaseSeriesDrawingProvider TypeDoc API and through practical examples such as custom line styling and dashed lines.
  • Interactive Modifiers: The use of the DataPointSelectionModifier enables interactive chart features. Users can click and drag to change selections on the chart, triggering a re-transformation of the render data. This interactivity is crucial for real-time updates and dynamic visual feedback, as described in the DataPoint Selection documentation.
  • Gradient Styling and Fills: The column series is styled with dynamic gradient fills using the GradientParams API. This creates a visually appealing differentiation between selected and unselected columns. For more on gradient fills in SciChart.js, see the GradientParams TypeDoc API.

Integration and Best Practices

The example is crafted entirely in JavaScript, showcasing how to integrate SciChart.js without relying on advanced frameworks. Despite the example being wrapped in a React component for display purposes, the core logic uses direct JavaScript calls to initialize the SciChartSurface, set up axes, create series, and apply interactivity. This approach highlights the benefits of leveraging WebAssembly for high performance while keeping the implementation straightforward. Developers are encouraged to review the Advanced JavaScript Chart and Graph Library documentation for more tailored strategies on integrating SciChart.js into JavaScript applications.

This comprehensive example not only provides a blueprint for multi-style series rendering but also demonstrates best practices in managing complex data transformations, interactivity, and performance optimizations in modern JavaScript charting.