Loading...
Most of G2's capabilities are exposed to users through the Chart
object. Here's an example of creating a simple bar chart:
(() => {const chart = new G2.Chart();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();return chart.getContainer();})();
Let's explore the core usage of the Chart
.
Every visualization in G2 is created by instantiating a new chart instance using the Chart
object:
import { Chart } from '@antv/g2';const chart = new Chart({/* chart options */});
You can specify some global options via new Chart(options)
, such as the mounting container, width, height, etc. All options are optional.
// Specify options as neededconst chart = new Chart({width: 800, // Chart widthheight: 400, // Chart heightcontainer: 'chart', // ID of the mounting container});
A chart instance must be mounted before it can be rendered on the screen. There are two ways to mount it.
<div id="chart"></div>
First method, automatic mounting.
const chart = new Chart({container: 'chart', // Specify the mounting container ID});// Orconst chart = new Chart({container: document.getElementById('chart'), // Specify the mounting container});
Second method, manual mounting.
const chart = new Chart();// Declare visualization// ...const container = chart.getContainer(); // Get the mounted containerdocument.getElementById('chart').appendChild(container);
Of course, you need to call chart.render
before the chart becomes visible.
// Create a chart instanceconst chart = new Chart({container: 'chart',});// Declare visualization// ...// Renderchart.render().then(() => {// Render successful}).catch((error) => {// Render failed});
When modifications are made to the declared visualization through the chart instance API, simply calling chart.render
again will update the chart.
// Initial renderchart.render();// Update declaration// ...// Update chartchart.render();
Clears the canvas and cancels event listeners. This also clears chart configurations and is often used when drawing a new chart.
chart.clear();
Destroys the canvas and cancels event listeners. This is often used when destroying components and pages.
chart.destroy();