JavaScript Quadrant Chart using Background Annotations

Demonstrates how to color areas of the chart surface using background Annotations using SciChart.js, High Performance JavaScript Charts

Fullscreen

Edit

 Edit

Docs

drawExample.ts

index.html

vanilla.ts

theme.ts

data.ts

Copy to clipboard
Minimise
Fullscreen
1import { appTheme } from "../../../theme";
2import { happinessData } from "./data";
3import {
4    SciChartSurface,
5    NumericAxis,
6    NumberRange,
7    ZoomPanModifier,
8    BoxAnnotation,
9    TextAnnotation,
10    EAnnotationLayer,
11    NativeTextAnnotation,
12    EAxisAlignment,
13    MouseWheelZoomModifier,
14    FastBubbleRenderableSeries,
15    XyzDataSeries,
16    IPointMetadata,
17    ZoomExtentsModifier,
18    EllipsePointMarker,
19    CursorModifier,
20    LogarithmicAxis,
21    ENumericFormat,
22    DefaultPaletteProvider,
23    TPointMarkerArgb,
24    parseColorToUIntArgb,
25    EHorizontalTextPosition,
26    EVerticalTextPosition,
27    SeriesInfo,
28    XyzSeriesInfo,
29    SweepAnimation,
30    ECoordinateMode,
31    EVerticalAnchorPoint,
32    SciChartLegend,
33    ManualLegend,
34} from "scichart";
35
36class ContinentPaletteProvider extends DefaultPaletteProvider {
37    Europe = parseColorToUIntArgb(appTheme.VividBlue);
38    Asia = parseColorToUIntArgb(appTheme.VividPurple);
39    NorthAmerica = parseColorToUIntArgb(appTheme.VividPink);
40    Oceania = parseColorToUIntArgb(appTheme.VividTeal);
41    SouthAmerica = parseColorToUIntArgb(appTheme.VividGreen);
42    Africa = parseColorToUIntArgb(appTheme.VividOrange);
43
44    override overridePointMarkerArgb(
45        xValue: number,
46        yValue: number,
47        index: number,
48        opacity?: number,
49        metadata?: IPointMetadata
50    ): TPointMarkerArgb {
51        let fill: number;
52        // @ts-ignore
53        switch (metadata.continent) {
54            case "Europe":
55                fill = this.Europe;
56                break;
57            case "Asia":
58                fill = this.Asia;
59                break;
60            case "North America":
61                fill = this.NorthAmerica;
62                break;
63            case "Oceania":
64                fill = this.Oceania;
65                break;
66            case "South America":
67                fill = this.SouthAmerica;
68                break;
69            case "Africa":
70                fill = this.Africa;
71                break;
72            default:
73                break;
74        }
75        return { fill, stroke: undefined };
76    }
77}
78
79export const drawExample = async (rootElement: string | HTMLDivElement) => {
80    // Create a SciChartSurface
81    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
82        theme: appTheme.SciChartJsTheme,
83        title: "Happiness vs GDP",
84        titleStyle: { fontSize: 20 },
85    });
86
87    // Create an XAxis and YAxis
88    const xAxis = new LogarithmicAxis(wasmContext, {
89        growBy: new NumberRange(0.1, 0.1),
90        labelPrefix: "$",
91        labelFormat: ENumericFormat.SignificantFigures,
92        labelPrecision: 2,
93        cursorLabelFormat: ENumericFormat.Decimal,
94        logBase: 10,
95        drawMinorGridLines: false,
96        axisTitle: "GDP per Capita",
97        axisTitleStyle: { fontSize: 16 },
98    });
99    sciChartSurface.xAxes.add(xAxis);
100
101    const yAxis = new NumericAxis(wasmContext, {
102        growBy: new NumberRange(0.1, 0.1),
103        axisAlignment: EAxisAlignment.Left,
104        drawMinorGridLines: false,
105        axisTitle: "Happiness",
106        axisTitleStyle: { fontSize: 16 },
107    });
108    sciChartSurface.yAxes.add(yAxis);
109
110    // Optional: Add some interactivity modifiers
111    sciChartSurface.chartModifiers.add(
112        new ZoomPanModifier({ enableZoom: true }),
113        new MouseWheelZoomModifier(),
114        new ZoomExtentsModifier(),
115        new CursorModifier({
116            showTooltip: true,
117            hitTestRadius: 1,
118            tooltipContainerBackground: appTheme.MutedRed,
119            showAxisLabels: false,
120            showXLine: false,
121            showYLine: false,
122            tooltipDataTemplate: (seriesInfos: SeriesInfo[], tooltipTitle: string) => {
123                const valuesWithLabels: string[] = [];
124                const xyzSeriesInfo = seriesInfos[0] as XyzSeriesInfo;
125                if (xyzSeriesInfo?.isHit) {
126                    // @ts-ignore
127                    valuesWithLabels.push(`${xyzSeriesInfo.pointMetadata.name}`);
128                    valuesWithLabels.push(`GDP: ${xyzSeriesInfo.formattedXValue}`);
129                    valuesWithLabels.push(`Happiness: ${xyzSeriesInfo.formattedYValue}`);
130                    valuesWithLabels.push(`Population: ${xyzSeriesInfo.formattedZValue}`);
131                }
132                return valuesWithLabels;
133            },
134        })
135    );
136
137    // These boxes are set up so that x1,y1 is the outer corner and x2,y2 is the centre of the data
138    const x2 = 10000;
139    const y2 = 5;
140    const box1 = new BoxAnnotation({
141        annotationLayer: EAnnotationLayer.Background,
142        fill: appTheme.PaleBlue,
143        strokeThickness: 0,
144        x1: -10,
145        x2,
146        y1: 10,
147        y2,
148    });
149    const box2 = new BoxAnnotation({
150        annotationLayer: EAnnotationLayer.Background,
151        fill: appTheme.PalePurple,
152        strokeThickness: 0,
153        x1: 10,
154        x2,
155        y1: 10,
156        y2,
157    });
158    const box3 = new BoxAnnotation({
159        annotationLayer: EAnnotationLayer.Background,
160        fill: appTheme.PalePink,
161        strokeThickness: 0,
162        x1: -10,
163        x2,
164        y1: -10,
165        y2,
166    });
167    const box4 = new BoxAnnotation({
168        annotationLayer: EAnnotationLayer.Background,
169        fill: appTheme.PaleTeal,
170        strokeThickness: 0,
171        x1: 10,
172        x2,
173        y1: -10,
174        y2,
175    });
176
177    // update the outer corners of each box before the chart draws so that they always fill the plane
178    sciChartSurface.preRender.subscribe((data) => {
179        box1.x1 = xAxis.visibleRange.min;
180        box2.x1 = xAxis.visibleRange.max;
181        box3.x1 = xAxis.visibleRange.min;
182        box4.x1 = xAxis.visibleRange.max;
183        box1.y1 = yAxis.visibleRange.min;
184        box2.y1 = yAxis.visibleRange.min;
185        box3.y1 = yAxis.visibleRange.max;
186        box4.y1 = yAxis.visibleRange.max;
187    });
188    sciChartSurface.annotations.add(box1, box2, box3, box4);
189    const xValues: number[] = [];
190    const yValues: number[] = [];
191    const zValues: number[] = [];
192    const metadata: any[] = [];
193    for (const item of happinessData) {
194        xValues.push(parseFloat(item.GDP));
195        yValues.push(parseFloat(item.Happiness));
196        zValues.push((Math.log2(parseInt(item.Population)) - 18) * 5);
197        //console.log(item.Entity, parseFloat(item.GDP), parseFloat(item.Happiness));
198        metadata.push({ isSelected: false, name: item.Entity, continent: item.Continent });
199    }
200    const dataSeries = new XyzDataSeries(wasmContext, { xValues, yValues, zValues, metadata });
201    const series = new FastBubbleRenderableSeries(wasmContext, {
202        dataSeries,
203        paletteProvider: new ContinentPaletteProvider(),
204        pointMarker: new EllipsePointMarker(wasmContext, {
205            width: 64,
206            height: 64,
207            opacity: 0.6,
208        }),
209        dataLabels: {
210            color: "#000000C0",
211            style: {
212                fontFamily: "Arial",
213                fontSize: 14,
214            },
215            horizontalTextPosition: EHorizontalTextPosition.Center,
216            verticalTextPosition: EVerticalTextPosition.Below,
217            metaDataSelector: (metadata) => (metadata as any).name,
218        },
219        animation: new SweepAnimation({ duration: 2000 }),
220    });
221    sciChartSurface.renderableSeries.add(series);
222
223    const legend = new ManualLegend(
224        {
225            textColor: "black",
226            backgroundColor: "#E0E0E077",
227            items: [
228                {
229                    name: "Bubble size represents population",
230                    color: "transparent",
231                    id: "pop",
232                    checked: false,
233                    showMarker: false,
234                },
235                {
236                    name: "Bubble color indicates continent",
237                    color: "transparent",
238                    id: "col",
239                    checked: false,
240                    showMarker: false,
241                },
242                { name: "Europe", color: appTheme.VividBlue, id: "Europe", checked: false },
243                { name: "Asia", color: appTheme.VividPurple, id: "Asia", checked: false },
244                { name: "North America", color: appTheme.VividPink, id: "NorthAmerica", checked: false },
245                { name: "South America", color: appTheme.VividGreen, id: "SouthAmerica", checked: false },
246                { name: "Oceania", color: appTheme.VividBlue, id: "VividTeal", checked: false },
247                { name: "Africa", color: appTheme.VividOrange, id: "Africa", checked: false },
248            ],
249        },
250        sciChartSurface
251    );
252
253    sciChartSurface.zoomExtents();
254    return { sciChartSurface, wasmContext };
255};
256

See Also: JavaScript Chart Types (28 Demos)

JavaScript Line Chart | JavaScript Chart Examples | SciChart | SciChart.js Demo

JavaScript Line Chart

Discover how to create a high performance JavaScript Line Chart with SciChart - the leading JavaScript library. Get your free demo now.

JavaScript Spline Line Chart | JavaScript Chart Library | SciChart.js Demo

JavaScript Spline Line Chart

Discover how to create a JavaScript Spline Line Chart with SciChart. Demo includes algorithm for smoother lines. Get your free trial now.

JavaScript Digital Line Chart | JavaScript Charts | View Now | SciChart.js Demo

JavaScript Digital Line Chart

Discover how to create a JavaScript Digital Line Chart with SciChart - your feature-rich JavaScript Chart Library. Get your free demo now.

JavaScript Band Chart | JavaScript Charts | View Examples | SciChart.js Demo

JavaScript Band Chart

Easily create a JavaScript Band Chart or High-Low Fill with SciChart - high performance JavaScript Chart Library. Get your free trial now.

JavaScript Spline Band Chart | JavaScript Charts | SciChart | SciChart.js Demo

JavaScript Spline Band Chart

SciChart's JavaScript Spline Band Chart makes it easy to draw thresholds or fills between two lines on a chart. Get your free demo today.

JavaScript Digital Band Chart | JavaScript Chart Library | SciChart.js Demo

JavaScript Digital Band Chart

Learn how to create a JavaScript Digital Band Chart or High-Low Fill Chart with SciChart's easy-to-follow demos. Get your free trial today.

JavaScript Bubble Chart | Online JavaScript Chart Examples | SciChart.js Demo

JavaScript Bubble Chart

Create a high performance JavaScript Bubble Chart with Sci-Chart. Demo shows how to draw point-markers at X,Y locations. Get your free demo now.

JavaScript Candlestick Chart | Chart Examples | SciChart.js | SciChart.js Demo

JavaScript Candlestick Chart

Discover how to create a JavaScript Candlestick Chart or Stock Chart using SciChart.js. For high Performance JavaScript Charts, get your free demo now.

JavaScript Column Chart | JavaScript Charts | SciChart.js | SciChart.js Demo

JavaScript Column Chart

JavaScript Column Chart demo by SciChart supports gradient fill and paletteproviders for more custom coloring options. Get your free demo now.

JavaScript Population Pyramid | SciChart.js Demo

JavaScript Population Pyramid

Population Pyramid of Europe and Africa

JavaScript Error Bars Chart |  Online Examples | SciChart.js | SciChart.js Demo

JavaScript Error Bars Chart

Create JavaScript Error Bars Chart using high performance SciChart.js. Display uncertainty or statistical confidence of a data-point. Get free demo now.

JavaScript Impulse Chart | JavaScript Charts | View Online | SciChart.js Demo

JavaScript Impulse Chart

Easily create JavaScript Impulse Chart or Stem Chart using SciChart.js - our own high performance JavaScript Chart Library. Get your free trial now.

JavaScript Text Chart | SciChart.js Demo

JavaScript Text Chart

Create JavaScript Text Chart with high performance SciChart.js.

JavaScript Fan Chart | JavaScript Chart Library | View Now | SciChart.js Demo

JavaScript Fan Chart

Discover how to create JavaScript Fan Chart with SciChart. Zoom in to see the detail you can go to using our JavaScript Charts. Get your free demo today.

JavaScript Heatmap Chart | JavaScript Chart Library Examples | SciChart.js Demo

JavaScript Heatmap Chart

Easily create a high performance JavaScript Heatmap Chart with SciChart. Get your free trial of our 5-star rated JavaScript Chart Component today.

JavaScript Non Uniform Heatmap Chart | JavaScript Chart Library Examples | SciChart.js Demo

JavaScript Non Uniform Heatmap Chart

Create JavaScript Non Uniform Chart using high performance SciChart.js. Display Heatmap with variable cell sizes. Get free demo now.

JavaScript Heatmap Chart With Contours Example | SciChart.js | SciChart.js Demo

JavaScript Heatmap Chart With Contours

Design a highly dynamic JavaScript Heatmap Chart With Contours with SciChart's feature-rich JavaScript Chart Library. Get your free demo today.

JavaScript Mountain Chart | View Examples Now | SciChart.js | SciChart.js Demo

JavaScript Mountain Chart

Create JavaScript Mountain Chart with SciChart.js. Zero line can be zero or a specific value. Fill color can be solid or gradient as well. Get a free demo now.

JavaScript Spline Mountain Chart | JavaScript Chart Library | SciChart.js Demo

JavaScript Spline Mountain Chart

JavaScript Spline Mountain Chart design made easy. Use SciChart.js' JavaScript Charts for high performance, feature-rich designs. Get free demo now.

JavaScript Digital Mountain Chart | JavaScript Chart Example | SciChart.js Demo

JavaScript Digital Mountain Chart

Create JavaScript Digital Mountain Chart with a stepped-line visual effect. Get your free trial of SciChart's 5-star rated JavaScript Chart Component now.

JavaScript Realtime Mountain Chart | View Online At SciChart | SciChart.js Demo

JavaScript Realtime Mountain Chart

JavaScript Realtime Mountain Chart made easy. Add animated, real-time updates with SciChart.js - high performance JavaScript Charts. Get free trial now.

JavaScript Scatter Chart | JavaScript Charts | SciChart.js | SciChart.js Demo

JavaScript Scatter Chart

Create JavaScript Scatter Chart with high performance SciChart.js. Easily render pre-defined point types. Supports custom shapes. Get your free trial now.

JavaScript Stacked Column Chart | Online JavaScript Charts | SciChart.js Demo

JavaScript Stacked Column Chart

Discover how to create a JavaScript Stacked Column Chart using our feature-rich JavaScript Chart Library, SciChart.js. Get your free demo today!

JavaScript Stacked Group Column Chart | View Examples Now | SciChart.js Demo

JavaScript Stacked Column Side by Side

Design JavaScript Stacked Group Column Chart side-by-side using our 5-star rated JavaScript Chart Framework, SciChart.js. Get your free demo now.

JavaScript Stacked Mountain Chart | JavaScript Chart Library | SciChart.js Demo

JavaScript Stacked Mountain Chart

Design a high performance JavaScript Stacked Mountain Chart with SciChart.js - your one-stop JavaScript chart library. Get free demo now to get started.

JavaScript Smooth Stacked Mountain Chart | JavaScript Chart Library | SciChart.js Demo

JavaScript Smooth Stacked Mountain Chart

Design a high performance JavaScript Stacked Mountain Chart with SciChart.js - your one-stop JavaScript chart library. Get free demo now to get started.

JavaScript Pie Chart | JavaScript Chart Examples | SciChart | SciChart.js Demo

JavaScript Pie Chart

Easily create and customise a high performance JavaScript Pie Chart with 5-star rated SciChart.js. Get your free trial now to access the whole library.

JavaScript Donut Chart | JavaScript Charts | SciChart.js | SciChart.js Demo

JavaScript Donut Chart

Create JavaScript Donut Chart with 5-star rated SciChart.js chart library. Supports legends, text labels, animated updates and more. Get free trial now.

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