logo

G2

  • Docs
  • Chart Introduction
  • API
  • Examples
  • Theme
  • Ecosystem
  • Productsantv logo arrow
  • 5.3.3
  • Get Started
  • Introduction
    • What is G2
    • Use In Framework
    • Experimental Spec API
  • Core Concepts
    • Chart
      • Components of G2 Charts
      • How to Use Charts
    • Mark
      • overview
      • area
      • box
      • boxplot
      • cell
      • chord
      • density
      • gauge
      • heatmap
      • image
      • interval
      • line
      • lineX
      • lineY
      • link
      • liquid
      • sunburst
      • point
      • polygon
      • range
      • rangeX
      • rangeY
      • rect
      • shape
      • text
      • vector
      • wordCloud
    • View
    • Data
      • overview
      • custom
      • ema
      • fetch
      • filter
      • fold
      • inline
      • join
      • kde
      • log
      • map
      • pick
      • rename
      • slice
      • sort
      • sortBy
    • Encode
    • Scale
      • overview
      • band
      • linear
      • log
      • ordinal
      • point
      • pow
      • quantile
      • quantize
      • sqrt
      • threshold
      • time
    • Transform
      • overview
      • bin
      • binX
      • diffY
      • dodgeX
      • flexX
      • group
      • groupColor
      • groupX
      • groupY
      • jitter
      • jitterX
      • jitterY
      • normalizeY
      • pack
      • sample
      • select
      • selectX
      • selectX
      • sortColor
      • sortX
      • sortY
      • stackEnter
      • stackY
      • symmetryY
    • Coordinate
      • overview
      • fisheye
      • parallel
      • polar
      • radial
      • theta
      • transpose
      • cartesian3D
      • helix
    • Style
    • Animate
      • overview
      • fadeIn
      • fadeOut
      • growInX
      • growInY
      • morphing
      • pathIn
      • scaleInX
      • scaleInY
      • scaleOutX
      • scaleOutY
      • waveIn
      • zoomIn
      • zoomOut
    • State
    • Interaction
      • Overview
      • brushAxisHighlight
      • brushHighlight
      • brushXHighlight
      • brushYHighlight
      • brushFilter
      • brushXFilter
      • brushYFilter
      • chartIndex
      • elementHighlight
      • elementHighlightByColor
      • elementHighlightByX
      • elementSelect
      • elementSelectByColor
      • elementSelectByX
      • fisheye
      • legendFilter
      • legendHighlight
      • poptip
      • scrollbarFilter
      • sliderFilter
    • Composition
      • overview
      • facetCircle
      • facetRect
      • repeatMatrix
      • spaceFlex
      • spaceLayer
      • timingKeyframe
    • Theme
      • overview
      • Academy
      • classic
      • classicDark
    • event
    • Color
  • Chart API
  • Chart Component
    • 标题(Title)
    • Axis
    • Legend
    • Scrollbar
    • Slider
    • Tooltip
    • Label
  • Extra Topics
    • Graph
      • forceGraph
      • pack
      • sankey
      • tree
      • treemap
    • Geo
      • geoPath
      • geoView
    • 3D
      • Draw 3D Chart
      • point3D
      • line3D
      • interval3D
      • surface3D
    • Plugin
      • renderer
      • rough
      • lottie
      • a11y
    • Package on demand
    • Set pattern
    • Server-side rendering(SSR)
    • Spec Function Expression Support (Available in 5.3.0)
  • Whats New
    • New Version Features
    • Migration from v4 to v5
  • Frequently Asked Questions (FAQ)

Use In Framework

Previous
What is G2
Next
Experimental Spec API

Resources

Ant Design
Galacea Effects
Umi-React Application Framework
Dumi-Component doc generator
ahooks-React Hooks Library

Community

Ant Financial Experience Tech
seeconfSEE Conf-Experience Tech Conference

Help

GitHub
StackOverflow

more productsMore Productions

Ant DesignAnt Design-Enterprise UI design language
yuqueYuque-Knowledge creation and Sharing tool
EggEgg-Enterprise-class Node development framework
kitchenKitchen-Sketch Tool set
GalaceanGalacean-互动图形解决方案
xtechLiven Experience technology
© Copyright 2025 Ant Group Co., Ltd..备案号:京ICP备15032932号-38

Loading...

Here is a brief introduction to how to use G2 in some front-end frameworks. We will use different frameworks to achieve the following update effects of bar chart.

framework

Achieving this effect mainly relies on the following two functions.

// Render bar chart
function renderBarChart(container) {
const chart = new Chart({
container,
});
// Prepare data
const data = [
{ genre: 'Sports', sold: 275 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
];
// Declare visualization
chart
.interval() // Create an Interval tag
.data(data) // Bind data
.encode('x', 'genre') // Encode x channel
.encode('y', 'sold') // Encode y channel
.encode('key', 'genre') // Specify key
.animate('update', { duration: 300 }); // Specify the time to update the animation
// Render visualization
chart.render();
return chart;
}
//Update bar chart data
function updateBarChart(chart) {
// Get Interval Mark
const interval = chart.getNodesByType('interval')[0];
// Simulate and update Interval data
const newData = interval.data().map((d) => ({
...d,
sold: Math.random() * 400 + 100,
}));
interval.data(newData);
// Re-render
chart.render();
}

It should be noted here that in the framework, it is not recommended to use the new Chart({ container: 'id' }) to specify the container. Instead, use the HTML element directly as the container: new Chart({ container: HTMLContainer }). This is to prevent problems where different components have the same id and cannot be rendered predictably.

Next, let's take a look at how to use these two functions in the framework.

Vue

In Vue, the first step is to import the defined G2Demo component.

<!-- App.vue -->
<template>
<div id="app">
<G2Demo />
</div>
</template>
<script>
import G2Demo from './components/G2Demo';
export default {
name: 'App',
components: {
G2Demo,
},
};
</script>

Options API

If using Vue2 and Vue3 options API, you can define the G2Demo component as follows, complete code reference here.

<!-- components/G2Demo.vue -->
<template>
<div>
<div ref="container"></div>
<button @click="onClick">Update Data</button>
</div>
</template>
<script>
import { Chart } from '@antv/g2';
function renderBarChart(container) {
// as shown above
}
function updateBarChart(chart) {
// as shown above
}
export default {
name: 'G2Demo',
props: {},
mounted() {
// save the bar chart instance
this.chart = renderBarChart(this.$refs.container);
},
methods: {
onClick() {
updateBarChart(this.chart);
},
},
};
</script>

Composition API

If you use the composition API of Vue3, the implementation is as follows, complete code reference here.

<script setup>
import { onMounted, ref } from 'vue';
import { Chart } from '@antv/g2';
let chart;
const container = ref(null);
onMounted(() => {
chart = renderBarChart(container.value);
});
function onClick() {
updateBarChart(chart);
}
function renderBarChart(container) {
// as above
}
function updateBarChart(chart) {
// as above
}
</script>
<template>
<div>
<div ref="container"></div>
<button @click="onClick">Update Data</button>
</div>
</template>

React

In React, the first step is also to import the defined G2Demo component.

import './styles.css';
import G2Demo from './components/G2Demo';
export default function App() {
return (
<div className="App">
<G2Demo />
</div>
);
}

Next, define the G2Demo component, complete code reference here.

import { Chart } from '@antv/g2';
import { useEffect, useRef } from 'react';
export default function G2Demo() {
const container = useRef(null);
const chart = useRef(null);
useEffect(() => {
if (!chart.current) {
chart.current = renderBarChart(container.current);
}
}, []);
function renderBarChart(container) {
// as above
}
function updateBarChart(chart) {
// as above
}
return (
<div className="App">
<div ref={container}></div>
<button onClick={() => updateBarChart(chart.current)}>Update Data</button>
</div>
);
}