### Link Mark with Direct x, y Configuration Source: https://g2.antv.antgroup.com/en/manual/core/mark/link This example shows how to configure the 'x' and 'y' channels for a link mark by directly providing arrays for both the start and end points (e.g., ['x', 'x1'] and ['y', 'y1']). ```javascript { type: 'link', data: [ { x: 10, y: 10, x1: 20, y1: 20 }, ], encode: { x: ['x','x1'], y: ['y','y1'] } } ``` -------------------------------- ### Getting Started with Classic Theme Source: https://g2.antv.antgroup.com/en/manual/core/theme/classic This snippet shows how to initialize a G2 chart using the classic theme. Ensure the 'container' element is present in your HTML. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container' }); chart.options({ type: 'interval', paddingLeft: 80, theme: 'classic', data: { type: 'fetch', value: 'https://gw.alipayobjects.com/os/bmw-prod/f129b517-158d-41a9-83a3-3294d639b39e.csv', format: 'csv', }, encode: { x: 'state', y: 'population', color: 'age' }, transform: [ { type: 'sortX', by: 'y', reverse: true, slice: 6 }, { type: 'dodgeX' }, ], axis: { y: { labelFormatter: '~s' }, x: { zIndex: 1 } }, interaction: { tooltip: { shared: true }, elementHighlight: { background: true }, }, }); chart.render(); ``` -------------------------------- ### Complete View Configuration Example Source: https://g2.antv.antgroup.com/en/manual/core/view This example demonstrates a comprehensive configuration for a G2 View, including data, encoding, scales, coordinates, styles, axes, legends, tooltips, interactions, themes, and child marks. ```javascript ({ type: 'view', data: [ { type: 'A', value: 30 }, { type: 'B', value: 50 }, { type: 'C', value: 20 }, ], encode: { x: 'type', y: 'value' }, scale: { y: { nice: true } }, coordinate: { type: 'rect' }, style: { viewFill: '#f5f5f5' }, axis: { y: { grid: true } }, legend: { color: { position: 'top' } }, tooltip: { title: { field: 'type' }, items: [{ field: 'value' }], }, interaction: { elementHighlight: true }, theme: { color: ['#5B8FF9', '#5AD8A6', '#5D7092'] }, children: [ { type: 'interval' }, { type: 'line', style: { stroke: '#faad14' } }, ], }); ``` -------------------------------- ### Complete Classic Dark Theme Configuration Example Source: https://g2.antv.antgroup.com/en/manual/core/theme/classic-dark A comprehensive example demonstrating the classic dark theme with specific configurations for view background, plot background, and axis styles. This snippet shows how to apply a dark theme and customize grid and label colors for better readability. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container' }); chart.options({ type: 'line', theme: { type: 'classicDark', view: { viewFill: '#0f0f0f', plotFill: '#1a1a1a' }, }, data: [ { year: '2018', value: 30 }, { year: '2019', value: 40 }, { year: '2020', value: 35 }, { year: '2021', value: 50 }, { year: '2022', value: 49 }, { year: '2023', value: 70 }, ], encode: { x: 'year', y: 'value' }, style: { stroke: '#60a5fa', lineWidth: 3 }, axis: { x: { grid: true, gridStroke: '#fff', gridLineWidth: 2, labelFill: '#d1d5db', }, y: { grid: true, gridStroke: '#fff', gridLineWidth: 2, labelFill: '#d1d5db', }, }, }); chart.render(); ``` -------------------------------- ### Gauge with Thresholds Configuration Source: https://g2.antv.antgroup.com/en/manual/core/mark/gauge This example shows a gauge chart configuration that includes thresholds, alongside basic setup for container and height. It utilizes the 'gauge' type and specifies target, total, and name for the data value. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', height: 350, }); chart.options({ type: 'gauge', data: { value: { target: 159, total: 400, name: 'score', thresholds: [200, 400] }, ``` -------------------------------- ### G2 Chart with Inline Data Example Source: https://g2.antv.antgroup.com/en/manual/core/data/inline A complete example demonstrating how to initialize a G2 chart and render it with inline data. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); chart.options({ type: 'interval', data: [ { genre: 'Sports', sold: 275 }, { genre: 'Strategy', sold: 115 }, { genre: 'Action', sold: 120 }, { genre: 'Shooter', sold: 350 }, { genre: 'Other', sold: 150 }, ], encode: { x: 'genre', y: 'sold', }, }); chart.render(); ``` -------------------------------- ### Complete G2 Chart with Interactive Legend Configuration Source: https://g2.antv.antgroup.com/en/manual/faq This example demonstrates a full G2 chart setup with interactive controls for legend position, size, and padding. It includes data, encoding, and dynamic updates based on user selections. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', height: 400, width: 600, }); const container = chart.getContainer(); const data = [ { genre: 'Sports', sold: 50 }, { genre: 'Strategy', sold: 115 }, { genre: 'Action', sold: 120 }, { genre: 'Shooter', sold: 350 }, { genre: 'Other', sold: 150 }, ]; chart.options({ type: 'interval', data, encode: { x: 'genre', y: 'sold', color: 'genre' }, legend: { color: { position: 'top', layout: { justifyContent: 'center', // Horizontal center alignItems: 'flex-start', }, size: 60, // Control legend cross axis size length: 250, // Control legend main axis length crossPadding: 20, // Distance from chart }, }, }); // Create layout selector const controlPanel = document.createElement('div'); controlPanel.style.cssText = ` margin-bottom: 16px; padding: 16px; background: #f5f5f5; border-radius: 8px; display: grid; grid-template-columns: 1fr 1fr; gap: 16px; `; // Layout scenario selector const sceneContainer = document.createElement('div'); sceneContainer.innerHTML = ` `; const sceneSelect = document.createElement('select'); sceneSelect.style.cssText = 'width: 100%; padding: 4px;'; const scenes = [ { label: 'Top center (Dashboard style)', value: 'top-center' }, { label: 'Right vertical center (Detailed chart)', value: 'right-center' }, { label: 'Bottom left aligned (Space saving)', value: 'bottom-start' }, { label: 'Left bottom aligned', value: 'left-end' }, { label: 'Right top aligned (Compact)', value: 'right-start' }, ]; sceneSelect.innerHTML = scenes .map( (scene, index) => ``, ) .join(''); sceneContainer.appendChild(sceneSelect); // Size control const sizeContainer = document.createElement('div'); sizeContainer.innerHTML = `
20
60
250
`; controlPanel.appendChild(sceneContainer); controlPanel.appendChild(sizeContainer); const updateChart = () => { const selectedScene = sceneSelect.value; const crossPadding = parseInt(document.getElementById('crossPadding').value); ``` -------------------------------- ### Link Mark with Separate x, y, x1, y1 Configuration Source: https://g2.antv.antgroup.com/en/manual/core/mark/link This example demonstrates configuring the 'x', 'y', 'x1', and 'y1' channels for a link mark by mapping each to a distinct data field. This allows for explicit control over the start and end coordinates of each link. ```javascript { type: 'link', data: [ { x: 10, y: 10, x1: 20, y1: 20 }, ], encode: { x: 'x', y: 'y', x1:'x1',y1:'y1' } } ``` -------------------------------- ### Basic Fisheye Example Source: https://g2.antv.antgroup.com/en/manual/core/interaction/fisheye This example demonstrates how to initialize a G2 chart and enable the fisheye interaction with a point plot type. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); chart.options({ type: 'point', data: { type: 'fetch', value: 'https://gw.alipayobjects.com/os/antvdemo/assets/data/scatter.json', }, encode: { x: 'weight', y: 'height', color: 'gender', }, interaction: { fisheye: true }, }); chart.render(); ``` -------------------------------- ### Basic Highlight Example Source: https://g2.antv.antgroup.com/en/manual/core/interaction/element-highlight-by-x A complete example demonstrating the basic usage of the elementHighlightByX interaction in a G2 chart. It configures an interval chart with data fetching and interaction enabled. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); chart.options({ type: 'interval', paddingLeft: 50, data: { type: 'fetch', value: 'https://gw.alipayobjects.com/os/bmw-prod/f129b517-158d-41a9-83a3-3294d639b39e.csv', format: 'csv', }, encode: { x: 'state', y: 'population', color: 'age' }, transform: [ { type: 'sortX', by: 'y', reverse: true, slice: 6 }, { type: 'dodgeX' }, ], axis: { y: { labelFormatter: '~s' } }, interaction: { elementHighlightByX: true }, }); chart.render(); ``` -------------------------------- ### Basic brushXHighlight Example Source: https://g2.antv.antgroup.com/en/manual/core/interaction/brush-x-highlight A basic implementation of the brushXHighlight interaction in a G2 chart. This example fetches data and encodes x, y, and color, enabling the brushXHighlight interaction. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); chart.options({ type: 'point', autoFit: true, data: { type: 'fetch', value: 'https://gw.alipayobjects.com/os/basement_prod/6b4aa721-b039-49b9-99d8-540b3f87d339.json', }, encode: { x: 'height', y: 'weight', color: 'gender' }, state: { inactive: { stroke: 'gray' } }, interaction: { brushXHighlight: true }, }); chart.render(); ``` -------------------------------- ### Complete G2 Chart State and Interaction Example Source: https://g2.antv.antgroup.com/en/manual/faq This example demonstrates a complete configuration for an interval chart, including data, state styles for active and selected states, and enabling element highlight and selection interactions. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); chart.options({ type: 'interval', data: [ { letter: 'A', frequency: 0.08167 }, { letter: 'B', frequency: 0.01492 }, { letter: 'C', frequency: 0.02782 }, ], encode: { x: 'letter', y: 'frequency' }, state: { // On hover: green fill + black stroke active: { fill: 'green', stroke: 'black', strokeWidth: 1 }, // On selection: red fill (overrides active fill) + keeps active stroke selected: { fill: 'red' }, }, interaction: { elementHighlight: true, elementSelect: true }, }); chart.render(); ``` -------------------------------- ### Example: Basic Legend Highlight Functionality Source: https://g2.antv.antgroup.com/en/manual/core/interaction/legend-highlight Demonstrates the core functionality of the legendHighlight interaction. This example sets up an interval chart and enables legend highlighting with series-level highlighting. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); chart.options({ type: 'interval', autoFit: true, height: 300, data: [ { name: 'London', month: 'Jan.', value: 18.9 }, { name: 'London', month: 'Feb.', value: 28.8 }, { name: 'London', month: 'Mar.', value: 39.3 }, { name: 'London', month: 'Apr.', value: 81.4 }, { name: 'London', month: 'May', value: 47 }, { name: 'London', month: 'Jun.', value: 20.3 }, { name: 'London', month: 'Jul.', value: 24 }, { name: 'London', month: 'Aug.', value: 35.6 }, { name: 'Berlin', month: 'Jan.', value: 12.4 }, { name: 'Berlin', month: 'Feb.', value: 23.2 }, { name: 'Berlin', month: 'Mar.', value: 34.5 }, { name: 'Berlin', month: 'Apr.', value: 99.7 }, { name: 'Berlin', month: 'May', value: 52.6 }, { name: 'Berlin', month: 'Jun.', value: 35.5 }, { name: 'Berlin', month: 'Jul.', value: 37.4 }, { name: 'Berlin', month: 'Aug.', value: 42.4 }, ], encode: { x: 'month', y: 'value', color: 'name', }, transform: [ { type: 'dodgeX', groupBy: 'x', orderBy: 'value', padding: 0.1, }, ], interaction: { legendHighlight: { series: true, }, }, state: { inactive: { opacity: 0.5 } }, }); chart.render(); ``` -------------------------------- ### Basic Gauge Chart Setup Source: https://g2.antv.antgroup.com/en/manual/core/mark/gauge This snippet demonstrates the fundamental setup for a gauge chart in G2. It requires importing the Chart class and configuring the container, chart type, and basic data values (target, total, name). ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); chart.options({ type: 'gauge', // Set the chart type to gauge data: { value: { target: 120, // Target value of the gauge total: 400, // Total value of the gauge name: 'score', // Name of the gauge data }, }, }); chart.render(); ``` -------------------------------- ### Quantile Scale Mapping Example Source: https://g2.antv.antgroup.com/en/manual/core/scale/quantile Demonstrates how to use the quantile scale to map continuous data to a range, showing data density. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); chart.options({ type: 'view', autoFit: true, data: [ { year: '1991', value: 3 }, { year: '1992', value: 4 }, { year: '1993', value: 3 }, { year: '1994', value: 5 }, { year: '1995', value: 4 }, { year: '1996', value: 5 }, { year: '1997', value: 7 }, { year: '1998', value: 7 }, { year: '1999', value: 13 }, ], encode: { x: 'year', y: 'value' }, scale: { y: { type: 'quantile', range: [1, 0.5, 0], }, }, children: [ { type: 'line', labels: [{ text: 'value', style: { dx: -10, dy: -12 } }] }, { type: 'point', style: { fill: 'white' }, tooltip: false }, ], }); chart.render(); ``` -------------------------------- ### Configure elementHighlightByX with Options Source: https://g2.antv.antgroup.com/en/manual/core/interaction/element-highlight-by-x Enables the elementHighlightByX interaction and configures it by passing an options object. This example enables the background highlight. ```javascript ({ type: 'line', interaction: { elementHighlightByX: { background: true, }, }, }); ``` -------------------------------- ### Example: Creating a Path Handle Source: https://g2.antv.antgroup.com/en/manual/core/interaction/brush-highlight Demonstrates how to create a custom path handle for interactions. This includes logic for initial creation and subsequent updates based on options. ```javascript function renderPath(group, options, document) { // Creation logic // If it's the first render, create and mount the graphic if (!group.handle) { // Create graphics through document.createElement const path = document.createElement('path'); group.handle = path; group.appendChild(group.handle); } // Update logic const { handle } = group; const { width, height, ...rest } = options; if (width === undefined || height === undefined) return handle; handle.attr(rest); // Return corresponding value return handle; } ``` -------------------------------- ### Getting Started with elementHighlightByX Source: https://g2.antv.antgroup.com/en/manual/core/interaction/element-highlight-by-x Initializes a G2 chart and enables the elementHighlightByX interaction with default settings. This snippet fetches data and renders an interval chart. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container' }); chart.options({ type: 'interval', paddingLeft: 50, data: { type: 'fetch', value: 'https://gw.alipayobjects.com/os/bmw-prod/f129b517-158d-41a9-83a3-3294d639b39e.csv', format: 'csv', }, encode: { x: 'state', y: 'population', color: 'age' }, transform: [ { type: 'sortX', by: 'y', reverse: true, slice: 6 }, { type: 'dodgeX' }, ], state: { active: { fill: 'red' }, inactive: { opacity: 0.5 } }, axis: { y: { labelFormatter: '~s' } }, interaction: { elementHighlightByX: true }, }); chart.render(); ``` -------------------------------- ### Initialize G2 with Lite Library (with Tooltip Interaction) Source: https://g2.antv.antgroup.com/en/manual/extra-topics/bundle Demonstrates on-demand import of the Tooltip interaction with G2.litelib. Configure interactions in the chart options. ```javascript import { Runtime, extend, litelib, Interval, Tooltip } from '@antv/g2'; const Chart = extend(Runtime, { ...litelib, 'mark.interval': Interval, 'interaction.tooltip': Tooltip, }); const chart = new Chart(); chart.options({ type: 'interval', interaction: { tooltip: true }, // 使用 tooltip 交互 }); ``` -------------------------------- ### Initialize G2 with 3D Library Source: https://g2.antv.antgroup.com/en/manual/extra-topics/bundle Set up G2 for 3D visualization using G2.corelib and G2.threedlib. Requires a WebGL renderer and setting the depth. ```javascript import { Runtime, extend, corelib } from '@antv/g2'; import { threedlib } from '@antv/g2-extension-3d'; import { Renderer } from '@antv/g-webgl'; const Chart = extend(Runtime, { ...corelib(), ...threedlib(), }); const chart = new Chart({ renderer: new Renderer(), //Use webgl renderer depth: 400, // Set depth }); chart.point3D(); ``` -------------------------------- ### G2 Library Components Example Source: https://g2.antv.antgroup.com/en/manual/extra-topics/bundle Illustrates the structure of the G2 library, showing how different visualization components are mapped to their respective implementations. This is key to understanding how on-demand packaging works by selecting specific components. ```javascript const library = { 'mark.interval': Interval, 'mark.forceGraph': ForceGraph, 'mark.geoPath': GeoPath, 'scale.linear': Linear, 'scale.log': Log, //... }; ``` -------------------------------- ### 3D Point with Sphere Shape and Lighting Source: https://g2.antv.antgroup.com/en/manual/extra-topics/three-dimensional/point-threed Demonstrates how to render a 3D point chart using the 'sphere' shape. This example includes setup for a WebGL renderer, 3D plugins, and a directional light source, which is necessary for 3D rendering. ```javascript import { Runtime, corelib, extend } from '@antv/g2'; import { threedlib } from '@antv/g2-extension-3d'; import { CameraType } from '@antv/g'; import { Renderer as WebGLRenderer } from '@antv/g-webgl'; import { Plugin as ThreeDPlugin, DirectionalLight } from '@antv/g-plugin-3d'; import { Plugin as ControlPlugin } from '@antv/g-plugin-control'; const renderer = new WebGLRenderer(); renderer.registerPlugin(new ControlPlugin()); renderer.registerPlugin(new ThreeDPlugin()); const Chart = extend(Runtime, { ...corelib(), ...threedlib(), }); // Initialize chart instance const chart = new Chart({ container: 'container', renderer, width: 500, height: 500, depth: 400, }); chart.options({ type: 'point3D', data: { type: 'fetch', value: 'https://gw.alipayobjects.com/os/bmw-prod/2c813e2d-2276-40b9-a9af-cf0a0fb7e942.csv', }, encode: { x: 'Horsepower', y: 'Miles_per_Gallon', z: 'Weight_in_lbs', color: 'Cylinders', shape: 'sphere' }, coordinate: { type: 'cartesian3D' }, scale: { x: { nice: true }, y: { nice: true }, z: { nice: true } }, legend: false, axis: { x: { gridLineWidth: 2 }, y: { gridLineWidth: 2, titleBillboardRotation: -Math.PI / 2 }, z: { gridLineWidth: 2 }, }, }); chart.render().then(() => { const { canvas } = chart.getContext(); const camera = canvas.getCamera(); camera.setPerspective(0.1, 5000, 45, 500 / 500); camera.setType(CameraType.ORBITING); // Add a directional light into scene. const light = new DirectionalLight({ style: { intensity: 3, fill: 'white', direction: [-1, 0, 1], }, }); canvas.appendChild(light); }); ``` -------------------------------- ### Basic Density Chart Setup Source: https://g2.antv.antgroup.com/en/manual/core/mark/density This snippet demonstrates how to initialize a G2 chart with the 'density' type, fetch data, apply a KDE transform, and encode visual channels. It's useful for creating density plots from JSON data. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', autoFit: true, }); chart.options({ type: 'density', data: { type: 'fetch', value: 'https://assets.antv.antgroup.com/g2/species.json', transform: [ { type: 'kde', field: 'y', groupBy: ['x'], size: 20, }, ], }, encode: { x: 'x', y: 'y', color: 'x', size: 'size' }, tooltip: false, }); chart.render(); ``` -------------------------------- ### Initialize G2 Runtime with Core Library Source: https://g2.antv.antgroup.com/en/manual/extra-topics/bundle Demonstrates how to initialize a G2 runtime and extend it with only the core library, which includes basic mark functionalities. This is useful for minimizing bundle size when only fundamental chart types are needed. ```javascript import { Runtime, extend, corelib } from '@antv/g2'; const Chart = extend(Runtime, corelib()); ``` -------------------------------- ### Link Mark with Arrows Source: https://g2.antv.antgroup.com/en/manual/core/mark/link This example demonstrates how to create a link mark with arrows to represent direction. It uses the 'x' and 'y' channels to define the start and end points of the links, and the 'color' channel to differentiate between link types. The 'arrow' style option is enabled. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); chart.options({ type: 'link', height: 260, autoFit: true, data: [ { x1: 10, y1: 10, x2: 20, y2: 20, type: '1' }, { x1: 21, y1: 12, x2: 11, y2: 22, type: '1' }, { x1: 20, y1: 21, x2: 10, y2: 11, type: '2' }, { x1: 11, y1: 23, x2: 21, y2: 13, type: '2' }, ], encode: { x: ['x1', 'x2'], y: ['y1', 'y2'], color: 'type' }, // The link mark requires x, x1, y, y1 channels to define a line or vector between two points style: { arrow: true, arrowSize: 6 }, // arrow is the arrow switch, arrows can usually represent direction, which is the difference between link and line marks. legend: false, }); chart.render(); ``` -------------------------------- ### Custom Handle Icon Shape for Slider Source: https://g2.antv.antgroup.com/en/manual/component/slider This example shows how to customize the handle icon shape of a slider using a function that returns a G2 display object. The function receives a type parameter ('start' or 'end') to differentiate between the left and right handles. ```javascript import { Chart } from '@antv/g2'; import { Circle } from '@antv/g'; const chart = new Chart({ container: 'container', autoFit: true, }); chart.options({ type: 'line', data: { type: 'fetch', value: 'https://gw.alipayobjects.com/os/bmw-prod/551d80c6-a6be-4f3c-a82a-abd739e12977.csv', }, encode: { x: 'date', y: 'close' }, slider: { x: { labelFormatter: (d) => new Date(d).toLocaleDateString(), style: { // Custom handle icon shape handleIconShape: (type) => { // type parameter is 'start' or 'end', representing left and right handles return new Circle({ style: { r: 8, fill: type === 'start' ? '#1890FF' : '#52C41A', stroke: '#fff', lineWidth: 2, shadowColor: type === 'start' ? '#1890FF' : '#52C41A', shadowBlur: 10, }, }); }, handleIconSize: 16, }, }, }, }); chart.render(); ``` -------------------------------- ### Initial Interval Chart Data Setup Source: https://g2.antv.antgroup.com/en/manual/core/data/overview This code initializes an interval chart with sample data. It sets up the chart container, defines the data, and encodes the 'genre' and 'sold' fields for the x and y axes respectively. The chart is then rendered. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); const interval = chart .interval() .data([ { genre: 'Sports', sold: 275 }, { genre: 'Strategy', sold: 115 }, { genre: 'Action', sold: 120 }, { genre: 'Shooter', sold: 350 }, { genre: 'Other', sold: 150 }, ]) .encode('x', 'genre') .encode('y', 'sold'); chart.render(); ``` -------------------------------- ### Beeswarm Plot with Color Encoding Source: https://g2.antv.antgroup.com/en/manual/core/mark/beeswarm This example shows how to add color encoding to a beeswarm plot in G2. The 'color' channel is mapped to a categorical field ('x' in this case) to distinguish different data groups. It requires the same setup as the basic beeswarm plot, with the addition of the 'color' property in the encode object. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); const data = Array.from({ length: 300 }, (_, i) => { return { x: `G${(i % 6) + 1}`, y: 40 + Math.random() * 220, }; }); chart.options({ type: 'beeswarm', data, encode: { x: 'x', y: 'y', size: 4, color: 'x', }, scale: { y: { nice: true, domainMin: 0, }, }, legend: { size: false, }, axis: { x: { title: false }, y: { title: false }, }, }); chart.render(); ``` -------------------------------- ### Initialize 3D Surface Chart Source: https://g2.antv.antgroup.com/en/manual/extra-topics/three-dimensional/surface-threed Demonstrates the setup for a 3D surface chart, including required renderers and plugins. Use this for creating interactive 3D visualizations. ```javascript import { Runtime, corelib, extend } from '@antv/g2'; import { threedlib } from '@antv/g2-extension-3d'; import { CameraType } from '@antv/g'; import { Renderer as WebGLRenderer } from '@antv/g-webgl'; import { Plugin as ThreeDPlugin } from '@antv/g-plugin-3d'; import { Plugin as ControlPlugin } from '@antv/g-plugin-control'; const renderer = new WebGLRenderer(); renderer.registerPlugin(new ControlPlugin()); renderer.registerPlugin(new ThreeDPlugin()); const Chart = extend(Runtime, { ...corelib(), ...threedlib(), }); // Initialize chart instance const chart = new Chart({ container: 'container', renderer, width: 500, height: 500, depth: 400, }); // We set the width/height to 100; const size = 100; const points = []; for (let i = 0; i <= 2 * size; ++i) { const theta = (Math.PI * (i - size)) / size; for (let j = 0; j <= 2 * size; ++j) { var phi = (Math.PI * (j - size)) / size; const x = (10.0 + Math.cos(theta)) * Math.cos(phi); const y = (10.0 + Math.cos(theta)) * Math.sin(phi); points.push({ x: i, y: j, z: Math.sin(theta) * x * y, }); } } chart.options({ type: 'surface3D', data: points, encode: { x: 'x', y: 'y', z: 'z' }, coordinate: { type: 'cartesian3D' }, scale: { x: { nice: true }, y: { nice: true }, z: { nice: true } }, legend: false, axis: { x: { gridLineWidth: 1 }, y: { gridLineWidth: 1, titleBillboardRotation: -Math.PI / 2 }, z: { gridLineWidth: 1 }, }, }); chart.render().then(() => { const { canvas } = chart.getContext(); const camera = canvas.getCamera(); camera.setPerspective(0.1, 2000, 45, 500 / 500); camera.rotate(30, 30, 0); camera.dolly(60); camera.setType(CameraType.ORBITING); }); ``` -------------------------------- ### Install @antv/g-lottie-player Source: https://g2.antv.antgroup.com/en/manual/extra-topics/plugin/lottie Install the necessary player for Lottie animations using npm. ```bash npm install @antv/g-lottie-player --save ``` -------------------------------- ### DodgeX Transform Configuration Example Source: https://g2.antv.antgroup.com/en/manual/core/transform/dodge-x Demonstrates the application of the dodgeX transform with various configuration options including groupBy, orderBy, reverse, and padding. This helps in visualizing data comparison across different series within groups. ```javascript import { registerTransform } from '@antv/g2'; registerTransform('dodgeX', () => { return ( { type: 'dodgeX', // Group data by the 'x' channel (Quarter) groupBy: 'x', // Sort elements within groups by their 'value' orderBy: 'value', // Reverse the order of elements within groups reverse: true, // Set spacing between elements within groups to 0.1 padding: 0.1 } ); }); ``` -------------------------------- ### Initialize with Options API, Update with Functional API Source: https://g2.antv.antgroup.com/en/manual/whats-new/new-version-features This example shows initializing a chart using the Options API and then updating its data using the Functional API. It includes a button to trigger data updates and re-renders the chart. ```javascript const { Chart } = G2; const chart = new Chart({ container: 'container', height: 150, padding: 10, }); const container = chart.getContainer(); const mock = () => Array.from({ length: 20 }, () => Math.random()); // Initialize chart // Use Options API chart.options({ type: 'interval', data: mock(), encode: { x: (_, i) => i, y: (d) => d, key: (_, i) => i }, axis: false, tooltip: { items: [{ channel: 'y', valueFormatter: '.0%' }], }, }); chart.render(); // Update chart // Use Functional API const button = document.createElement('button'); button.style.display = 'block'; button.textContent = 'Update Data'; button.onclick = () => { const interval = chart.getNodeByType('interval'); // Get interval interval.data(mock()); // Update interval data chart.render(); // Render chart }; container.insertBefore(button, container.childNodes[0]); ``` -------------------------------- ### Install @antv/g-pattern Dependency Source: https://g2.antv.antgroup.com/en/manual/extra-topics/pattern Install the necessary package for using pattern fills. ```bash $ npm install @antv/g-pattern --save; ``` -------------------------------- ### Initialize G2 with Lite Library (Basic) Source: https://g2.antv.antgroup.com/en/manual/extra-topics/bundle Use G2.litelib for a smaller G2 package, importing only essential components like Interval. Other components must be imported on demand. ```javascript import { Runtime, extend, litelib, Interval } from '@antv/g2'; const Chart = extend(Runtime, { ...litelib, 'mark.interval': Interval, }); const chart = new Chart(); chart.interval(); ``` -------------------------------- ### Field Encoding Example Source: https://g2.antv.antgroup.com/en/manual/core/encode Example of specifying field encoding for the x-channel of an interval mark. ```javascript ({ type: 'interval', encode: { x: { type: 'field', value: 'name' } }, }); ``` -------------------------------- ### Install @antv/g-plugin-a11y Source: https://g2.antv.antgroup.com/en/manual/extra-topics/plugin/a11y Install the accessibility plugin using npm. This is the first step before importing it into your project. ```bash npm install @antv/g-plugin-a11y --save ``` -------------------------------- ### Basic StackEnter Example Source: https://g2.antv.antgroup.com/en/manual/core/transform/stack-enter Demonstrates the usage of the stackEnter transformation for animating stacked interval charts. Ensure the G2 library is imported and a chart instance is created. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container' }); chart.options({ type: 'interval', data: [ { type: 'Apple', year: '2001', value: 260 }, { type: 'Orange', year: '2001', value: 100 }, { type: 'Banana', year: '2001', value: 90 }, { type: 'Apple', year: '2002', value: 210 }, { type: 'Orange', year: '2002', value: 150 }, { type: 'Banana', year: '2002', value: 30 }, ], encode: { x: 'year', y: 'value', color: 'type', series: 'type', enterDuration: 1000, }, transform: [{ type: 'stackEnter', groupBy: 'x' }], }); chart.render(); ``` -------------------------------- ### Connector with Dynamic Styling Source: https://g2.antv.antgroup.com/en/manual/core/mark/connector This example shows how to create a responsive connector where styles like stroke color, width, and intermediate segment length are determined by the data. It's useful for visualizing data attributes like type or weight. ```javascript const connector = new Connector({ stroke: (d) => (d.type === 'important' ? '#ff4d4f' : '#1890ff'), strokeWidth: (d) => d.weight || 1, connectLength1: (d) => d.distance || 20, }); ``` -------------------------------- ### Initialize G2 with Graph Library Source: https://g2.antv.antgroup.com/en/manual/extra-topics/bundle Initialize G2 with graph analysis capabilities using G2.corelib and G2.graphlib. This enables features like ForceGraph. ```javascript import { Runtime, extend, corelib, graphlib } from '@antv/g2'; const Chart = extend(Runtime, { ...corelib(), ...graphlib(), }); const chart = new Chart(); chart.forceGraph(); ``` -------------------------------- ### Get and Set Chart Configuration Options Source: https://g2.antv.antgroup.com/en/manual/api Use `attr()` to get all configuration options or set specific ones like padding. ```javascript const point = chart.point(); console.log(point.attr()); ``` ```javascript point.attr('padding', 0); ``` -------------------------------- ### Connector with Animations Source: https://g2.antv.antgroup.com/en/manual/core/mark/connector This example demonstrates how to apply default animations for entering, updating, and exiting states to a connector. It's useful for creating dynamic and visually engaging diagrams. ```javascript const connector = new Connector({ stroke: '#1890ff', strokeWidth: 2, defaultEnterAnimation: 'growIn', defaultUpdateAnimation: 'morphing', defaultExitAnimation: 'fadeOut', }); ``` -------------------------------- ### Point-Line Connection Graph with Annotations Source: https://g2.antv.antgroup.com/en/manual/core/mark/overview This example demonstrates creating a point-line connection graph with annotations by combining Point and Link marks. It fetches data and maps dimensions to x and y axes, with tooltips for interactivity. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', height: 180, }); chart.options({ type: 'view', data: { type: 'fetch', value: 'https://assets.antv.antgroup.com/g2/penguins.json', transform: [ { type: 'map', callback: (d) => ({ ...d, body_mass_g: +d.body_mass_g, }), }, ], }, children: [ // point mark { type: 'point', encode: { x: 'body_mass_g', y: 'species' }, style: { stroke: '#000' }, tooltip: { items: [{ channel: 'x' }] }, }, // link mark { type: 'link', encode: { x: 'body_mass_g', y: 'species' }, transform: [{ type: 'groupY', x: 'min', x1: 'max' }], style: { stroke: '#000' }, tooltip: false, }, // point mark for drawing median line { type: 'point', encode: { y: 'species', x: 'body_mass_g', shape: 'line', size: 12 }, transform: [{ type: 'groupY', x: 'median' }], style: { stroke: 'red' }, tooltip: { items: [{ channel: 'x' }] }, }, ], }); chart.render(); ``` -------------------------------- ### Initialize Point3D Chart with 3D Plugins Source: https://g2.antv.antgroup.com/en/manual/extra-topics/three-dimensional/point-threed Sets up the G2 chart instance with WebGL renderer, 3D plugins, and camera controls. This is the foundational setup for any 3D chart. ```javascript import { Runtime, corelib, extend } from '@antv/g2'; import { threedlib } from '@antv/g2-extension-3d'; import { CameraType } from '@antv/g'; import { Renderer as WebGLRenderer } from '@antv/g-webgl'; import { Plugin as ThreeDPlugin, DirectionalLight } from '@antv/g-plugin-3d'; import { Plugin as ControlPlugin } from '@antv/g-plugin-control'; const renderer = new WebGLRenderer(); renderer.registerPlugin(new ControlPlugin()); renderer.registerPlugin(new ThreeDPlugin()); const Chart = extend(Runtime, { ...corelib(), ...threedlib(), }); // Initialize chart instance const chart = new Chart({ container: 'container', renderer, width: 500, height: 500, depth: 400, }); chart.options({ type: 'point3D', data: { type: 'fetch', value: 'https://gw.alipayobjects.com/os/bmw-prod/2c813e2d-2276-40b9-a9af-cf0a0fb7e942.csv', }, encode: { x: 'Horsepower', y: 'Miles_per_Gallon', z: 'Weight_in_lbs', color: 'Cylinders', shape: 'cube' }, coordinate: { type: 'cartesian3D' }, scale: { x: { nice: true }, y: { nice: true }, z: { nice: true } }, legend: false, axis: { x: { gridLineWidth: 2 }, y: { gridLineWidth: 2, titleBillboardRotation: -Math.PI / 2 }, z: { gridLineWidth: 2 }, }, }); chart.render().then(() => { const { canvas } = chart.getContext(); const camera = canvas.getCamera(); camera.setPerspective(0.1, 5000, 45, 500 / 500); camera.setType(CameraType.ORBITING); // Add a directional light into scene. const light = new DirectionalLight({ style: { intensity: 3, fill: 'white', direction: [-1, 0, 1], }, }); canvas.appendChild(light); }); ``` -------------------------------- ### Linear Scale Comparison Example Source: https://g2.antv.antgroup.com/en/manual/core/scale/sqrt This example shows the same chart configuration but without the sqrt scale applied to the y-axis, illustrating the difference in data distribution compared to a linear scale. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); chart.options({ type: 'view', autoFit: true, data: [ { year: '1991', value: 1 }, { year: '1992', value: 4 }, { year: '1993', value: 9 }, { year: '1994', value: 16 }, { year: '1995', value: 25 }, ], encode: { x: 'year', y: 'value' }, children: [ { type: 'line', labels: [{ text: 'value', style: { dx: -10, dy: -12 } }] }, { type: 'point', style: { fill: 'white' }, tooltip: false }, ], }); chart.render(); ``` -------------------------------- ### G2 Fetch Data Source with Imports Source: https://g2.antv.antgroup.com/en/manual/core/data/fetch A complete example demonstrating how to initialize a G2 chart and configure it to fetch data from a remote JSON file. ```javascript import { Chart } from '@antv/g2'; const chart = new Chart({ container: 'container', }); chart.options({ type: 'point', data: { type: 'fetch', value: 'https://gw.alipayobjects.com/os/antvdemo/assets/data/scatter.json', }, encode: { x: 'weight', y: 'height', color: 'gender', }, }); chart.render(); ```