Angular Force Directed Graph

Creates an Angular Force Directed Graph using SciChart.js, visualizing US airport flight routes with a physics-based force simulation.

Fullscreen

Edit

 Edit

Docs

drawExample.ts

angular.ts

theme.ts

airportData.ts

nodeModifiers.ts

Copy to clipboard
Minimise
Fullscreen
1import {
2    SciChartSurface,
3    NumericAxis,
4    XyDataSeries,
5    XyxyDataSeries,
6    XyScatterRenderableSeries,
7    FastLineSegmentRenderableSeries,
8    EllipsePointMarker,
9    NumberRange,
10    ZoomPanModifier,
11    ZoomExtentsModifier,
12    MouseWheelZoomModifier,
13    EAutoRange,
14} from "scichart";
15import { appTheme } from "../../../theme";
16import {
17    SimNode,
18    SimEdge,
19    EdgeHoverState,
20    NodeTooltipModifier,
21    NodeDragModifier,
22    NodeHoverPaletteProvider,
23    DragStateRef,
24} from "./nodeModifiers";
25import { AIRPORTS, ROUTES } from "./airportData";
26
27// ─── Build simulation state ───────────────────────────────────────────────────
28
29function buildSimulation(): { nodes: SimNode[]; edges: SimEdge[] } {
30    const iataToIdx = new Map<string, number>();
31    const centerLon = -96;
32    const centerLat = 38;
33    const scaleX = 4.5;
34    const scaleY = 5.5;
35
36    const nodes: SimNode[] = AIRPORTS.map((a, i) => {
37        iataToIdx.set(a.iata, i);
38        const geoX = (a.lon - centerLon) * scaleX;
39        const geoY = (a.lat - centerLat) * scaleY;
40        return { iata: a.iata, label: `${a.iata}${a.city}, ${a.state}`, x: geoX, y: geoY, vx: 0, vy: 0, geoX, geoY };
41    });
42
43    const edges: SimEdge[] = ROUTES
44        .map(r => {
45            const si = iataToIdx.get(r.origin);
46            const ti = iataToIdx.get(r.destination);
47            if (si === undefined || ti === undefined) return null;
48            return { sourceIdx: si, targetIdx: ti };
49        })
50        .filter((e): e is SimEdge => e !== null);
51
52    return { nodes, edges };
53}
54
55// ─── Force simulation tick ────────────────────────────────────────────────────
56
57const REPULSION_STRENGTH = -120;
58const REPULSION_MIN_DIST = 1;
59const SPRING_K = 0.3;
60const SPRING_REST_LENGTH = 20;
61const GEO_ANCHOR_STRENGTH = 0.12;
62const VELOCITY_DECAY = 0.6;
63
64function tick(nodes: SimNode[], edges: SimEdge[], alpha: number): void {
65    for (let i = 0; i < nodes.length; i++) {
66        for (let j = i + 1; j < nodes.length; j++) {
67            const dx = nodes[j].x - nodes[i].x;
68            const dy = nodes[j].y - nodes[i].y;
69            const dist = Math.max(Math.sqrt(dx * dx + dy * dy), REPULSION_MIN_DIST);
70            const force = (REPULSION_STRENGTH * alpha) / (dist * dist);
71            const fx = force * (dx / dist);
72            const fy = force * (dy / dist);
73            nodes[i].vx += fx;
74            nodes[i].vy += fy;
75            nodes[j].vx -= fx;
76            nodes[j].vy -= fy;
77        }
78    }
79
80    for (const edge of edges) {
81        const src = nodes[edge.sourceIdx];
82        const tgt = nodes[edge.targetIdx];
83        const dx = (tgt.x + tgt.vx) - (src.x + src.vx);
84        const dy = (tgt.y + tgt.vy) - (src.y + src.vy);
85        const dist = Math.max(Math.sqrt(dx * dx + dy * dy), 1);
86        const force = SPRING_K * (dist - SPRING_REST_LENGTH) * alpha;
87        const fx = force * (dx / dist);
88        const fy = force * (dy / dist);
89        src.vx += fx * 0.5;
90        src.vy += fy * 0.5;
91        tgt.vx -= fx * 0.5;
92        tgt.vy -= fy * 0.5;
93    }
94
95    for (const node of nodes) {
96        node.vx += (node.geoX - node.x) * GEO_ANCHOR_STRENGTH * alpha;
97        node.vy += (node.geoY - node.y) * GEO_ANCHOR_STRENGTH * alpha;
98    }
99
100    for (const node of nodes) {
101        node.vx *= VELOCITY_DECAY;
102        node.vy *= VELOCITY_DECAY;
103        node.x += node.vx;
104        node.y += node.vy;
105    }
106}
107
108// ─── Chart initialization ─────────────────────────────────────────────────────
109
110export const drawExample = async (rootElement: string | HTMLDivElement) => {
111    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
112        theme: appTheme.SciChartJsTheme,
113    });
114
115    const xAxis = new NumericAxis(wasmContext, { isVisible: false, autoRange: EAutoRange.Never });
116    const yAxis = new NumericAxis(wasmContext, { isVisible: false, autoRange: EAutoRange.Never });
117    xAxis.visibleRange = new NumberRange(-300, 300);
118    yAxis.visibleRange = new NumberRange(-300, 300);
119    sciChartSurface.xAxes.add(xAxis);
120    sciChartSurface.yAxes.add(yAxis);
121
122    const { nodes, edges } = buildSimulation();
123
124    const edgeHover = new EdgeHoverState();
125
126    const edgeDataSeries = new XyxyDataSeries(wasmContext);
127    sciChartSurface.renderableSeries.add(new FastLineSegmentRenderableSeries(wasmContext, {
128        dataSeries: edgeDataSeries,
129        stroke: "#47bde650",
130        strokeThickness: 2,
131    }));
132
133    const edgeHighlightDataSeries = new XyxyDataSeries(wasmContext);
134    sciChartSurface.renderableSeries.add(new FastLineSegmentRenderableSeries(wasmContext, {
135        dataSeries: edgeHighlightDataSeries,
136        stroke: "#47bde6",
137        strokeThickness: 3,
138    }));
139
140    const nodeDataSeries = new XyDataSeries(wasmContext);
141    sciChartSurface.renderableSeries.add(new XyScatterRenderableSeries(wasmContext, {
142        dataSeries: nodeDataSeries,
143        pointMarker: new EllipsePointMarker(wasmContext, {
144            width: 10,
145            height: 10,
146            fill: "#274b92",
147            stroke: "#47bde6",
148            strokeThickness: 1.5,
149        }),
150        paletteProvider: new NodeHoverPaletteProvider(edgeHover),
151    }));
152
153    const dragState: DragStateRef = { current: null };
154
155    let alpha = 1.0;
156    let running = true;
157    let loopAlive = false;
158    let autoZoomed = false;
159    let animFrameId: number = 0;
160
161    function frame() {
162        if (!running || sciChartSurface.isDeleted) { loopAlive = false; return; }
163
164        const simActive = alpha >= 0.001 || !!dragState.current;
165
166        if (simActive) {
167            tick(nodes, edges, alpha);
168            alpha *= 0.9772;
169
170            if (!autoZoomed && alpha < 0.5) {
171                autoZoomed = true;
172                sciChartSurface.zoomExtents(200);
173            }
174
175            if (dragState.current) {
176                const n = nodes[dragState.current.nodeIdx];
177                n.x = dragState.current.dataX;
178                n.y = dragState.current.dataY;
179                n.vx = 0;
180                n.vy = 0;
181                alpha = Math.max(alpha, 0.1);
182            }
183        }
184
185        const ex: number[] = [], ey: number[] = [], ex1: number[] = [], ey1: number[] = [];
186        const hx: number[] = [], hy: number[] = [], hx1: number[] = [], hy1: number[] = [];
187        const h = edgeHover.hoveredNodeIdx;
188        for (const edge of edges) {
189            const src = nodes[edge.sourceIdx], tgt = nodes[edge.targetIdx];
190            if (h !== -1 && (edge.sourceIdx === h || edge.targetIdx === h)) {
191                hx.push(src.x); hy.push(src.y); hx1.push(tgt.x); hy1.push(tgt.y);
192            } else {
193                ex.push(src.x); ey.push(src.y); ex1.push(tgt.x); ey1.push(tgt.y);
194            }
195        }
196        edgeDataSeries.clear();
197        edgeDataSeries.appendRange(ex, ey, ex1, ey1);
198        edgeHighlightDataSeries.clear();
199        edgeHighlightDataSeries.appendRange(hx, hy, hx1, hy1);
200
201        nodeDataSeries.clear();
202        nodeDataSeries.appendRange(nodes.map(n => n.x), nodes.map(n => n.y));
203
204        if (simActive) {
205            animFrameId = requestAnimationFrame(frame);
206        } else {
207            loopAlive = false;
208        }
209    }
210
211    function startLoop() {
212        if (!loopAlive) {
213            loopAlive = true;
214            animFrameId = requestAnimationFrame(frame);
215        }
216    }
217
218    sciChartSurface.chartModifiers.add(
219        new NodeTooltipModifier(nodes, edges, edgeHover, () => startLoop()),
220        new NodeDragModifier(nodes, dragState, () => { alpha = Math.max(alpha, 0.3); startLoop(); }),
221        new ZoomPanModifier(),
222        new ZoomExtentsModifier(),
223        new MouseWheelZoomModifier()
224    );
225
226    startLoop();
227
228    return {
229        sciChartSurface,
230        wasmContext,
231        stopAnimation: () => {
232            running = false;
233            if (animFrameId) cancelAnimationFrame(animFrameId);
234        },
235    };
236};
237

Force Directed Graph (Angular)

Overview

This example demonstrates a Force Directed Graph built with SciChart.js in Angular, visualizing ~60 US airports connected by ~2300 flight routes. The graph uses a custom physics simulation to position nodes, with geographic anchoring that keeps airports near their real-world lat/lon positions.

Technical Implementation

The chart is initialized using the [initChart] property binding with the drawExample function. Edges are rendered using FastLineSegmentRenderableSeries with an XyxyDataSeries. Airport nodes are rendered as XyScatterRenderableSeries with EllipsePointMarker. The physics loop uses requestAnimationFrame and applies repulsion, spring, and geographic anchor forces each tick.

Interactivity

Two custom ChartModifierBase2D subclasses provide interactivity: NodeTooltipModifier highlights connected routes and labels neighbours on hover, and NodeDragModifier allows dragging nodes to explore the graph structure. Standard ZoomPanModifier and MouseWheelZoomModifier are also included.

angular Chart Examples & Demos

See Also: JavaScript Chart Types (40 Demos)

Angular Line Chart | Angular Charts | SciChart.js Demo

Angular Line Chart

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

Angular Spline Line Chart | Angular Charts | SciChart.js Demo

Angular Spline Line Chart

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

Angular Digital Line Chart | Angular Charts | SciChart.js

Angular Digital Line Chart

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

Angular Band Chart | Angular Charts | SciChart.js Demo

Angular Band Chart

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

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

Angular Spline Band Chart

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

Angular Digital Band Chart | Angular Charts | SciChart.js

Angular Digital Band Chart

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

Angular Bubble Chart | Online JavaScript Chart Examples

Angular Bubble Chart

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

Angular Candlestick Chart | Online JavaScript Chart Examples

Angular Candlestick Chart

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

Angular Column Chart | Angular Charts | SciChart.js Demo

Angular Column Chart

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

Angular Population Pyramid | Angular Charts | SciChart.js

Angular Population Pyramid

Population Pyramid of Europe and Africa

Angular Error Bars Char | Angular Charts | SciChart.js Demo

Angular Error Bars Chart

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

Angular Impulse Chart | Angular Charts | SciChart.js Demo

Angular Impulse Chart

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

Angular Text Chart | Angular Charts | SciChart.js Demo

Angular Text Chart

Create Angular Text Chart with high performance SciChart.js.

Angular Fan Chart | Angular Charts | SciChart.js Demo

Angular Fan Chart

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

Angular Heatmap Chart | Angular Charts | SciChart.js Demo

Angular Heatmap Chart

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

Angular Non Uniform Heatmap Chart | SciChart.js Demo

Angular Non Uniform Heatmap Chart

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

Angular Heatmap Chart With Contours | SciChart.js Demo

Angular Heatmap Chart With Contours Example

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

NEW!
Angular Map Chart with Heatmap overlay | SciChart.js Demo

Angular Map Chart with Heatmap overlay

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

Angular Mountain Chart | Angular Charts | SciChart.js Demo

Angular Mountain Chart

Create Angular 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.

Angular Spline Mountain Chart | Angular Charts | SciChart.js

Angular Spline Mountain Chart

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

Angular Digital Mountain Chart | Angular Charts | SciChart.js

Angular Digital Mountain Chart

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

Angular Realtime Mountain Chart | View Online At SciChart

Angular Realtime Mountain Chart

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

Angular Scatter Chart | Angular Charts | SciChart.js Demo

Angular Scatter Chart

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

Angular Stacked Column Chart | Online JavaScript Charts

Angular Stacked Column Chart

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

Angular Stacked Group Column Chart | View Examples Now

Angular Stacked Column Side by Side

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

Angular Stacked Mountain Chart | Angular Charts | SciChart.js

Angular Stacked Mountain Chart

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

Angular Smooth Stacked Mountain Chart | SciChart.js Demo

Angular Smooth Stacked Mountain Chart

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

Angular Pie Chart | Angular Charts | SciChart.js Demo

Angular Pie Chart

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

Angular Donut Chart | Angular Charts | SciChart.js Demo

Angular Donut Chart

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

Angular Linear Gauges | Angular Charts | SciChart.js Demo

Angular Linear Gauges Example

View the Angular Linear Gauge Chart example to combine rectangles & annotations. Create a linear gauge dashboard with animated indicators and custom scales.

Angular Quadrant Chart using Background Annotations

Angular Quadrant Chart using Background Annotations

Demonstrates how to color areas of the chart surface using background Annotations using SciChart.js Annotations API

Angular Histogram Chart | Angular Charts | SciChart.js Demo

Angular Histogram Chart

Create an Angular Histogram Chart with custom texture fills and patterns. Try the SciChartAngular wrapper component for seamless Angular integration today.

Angular Gantt Chart | Angular Charts | SciChart.js Demo

Angular Gantt Chart Example

Build an Angular Gantt Chart with SciChart. View the demo for horizontal bars, rounded corners and data labels to show project timelines and task completion.

Angular Choropleth Map | Angular Charts | SciChart.js Demo

Angular Choropleth Map Example

Create an Angular Choropleth map, a type of thematic map where areas are shaded or patterned in proportion to the value of a variable being represented.

Angular Multi-Layer Map | Angular Charts | SciChart.js Demo

Angular Multi-Layer Map Example

Create a Angular Multi-Layer Map Example, using FastTriangleRenderableSeries with GeoJSON data-points using a constrained delaunay triangulation algorithm.

Angular Vector Field Plot | Angular Charts | SciChart.js Demo

Angular Vector Field Plot

View the Angular Vector Field Plot example from SciChart, including dynamic vector generation, gradient-colored segments, and interactive zoom/pan. Try demo.

Angular Waterfall Chart | Bridge Chart | SciChart.js Demo

Angular Waterfall Chart | Bridge Chart

Build an Angular Waterfall Chart with dynamic coloring, multi-line data labels & responsive design, using ScichartAngular component for seamless integration

Angular Box Plot Chart | Angular Charts | SciChart.js Demo

Angular Box Plot Chart

Try the Angular Box Plot Chart example for Angular-friendly chart lifecycle management, dynamic sub-surface positioning, and custom styling. Try the demo now.

Angular Triangle Series | Triangle Mesh Chart | SciChart

Angular Triangle Series | Triangle Mesh Chart

Create Angular Triangle Meshes with the Triangle Series from SciChart. This demo supports strip mode, list mode and the drawing of polygons. View the example.

Angular Treemap Chart | Angular Charts | SciChart.js Demo

Angular Treemap Chart

Create an Angular Treemap Chart to define rectangle positions based on total value. Use SciChart FastRectangleRenderableSeries and d3-hierarchy.js layouts.

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