把G2引入angular项目
1、安装
npm install @antv/g2 --save
2、引入
import { Chart } from '@antv/g2';
之后就是使用了
使用
创建一个组件,并在这个组件内引入g2。
1、创建 div 图表容器
<div id="c1"></div>
2、创建 Chart 对象
const chart = new Chart({
container: 'c1', // 指定图表容器 ID
width: 600, // 指定图表宽度
height: 300, // 指定图表高度
});
3、载入数据源
const data = [
{ genre: 'Sports', sold: 275 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
];
// data是已经创建好的变量
chart.data(data);
4、创建图形语法,绘制柱状图
chart.interval().position('genre*sold');
5、渲染图表
chart.render();
写个方法,包括2~5步骤,然后在ngoninit()里调用这个方法就行
完整代码:
import { Component, OnInit } from '@angular/core';
import { Chart } from '@antv/g2';
@Component({
selector: 'app-antv',
templateUrl: './antv.component.html',
styleUrls: ['./antv.component.less']
})
export class AntvComponent implements OnInit {
data: any = [
{ genre: 'Sports', sold: 275 },
{ genre: 'Strategy', sold: 115 },
{ genre: 'Action', sold: 120 },
{ genre: 'Shooter', sold: 350 },
{ genre: 'Other', sold: 150 },
];
constructor() { }
ngOnInit(): void {
this.graph1();
}
// tslint:disable-next-line:typedef
graph1() {
// Step 1: 创建 Chart 对象
const chart = new Chart({
container: 'container', // 指定图表容器 ID
width: 600, // 指定图表宽度
height: 300, // 指定图表高度
});
// Step 2: 载入数据源
chart.data(this.data);
// Step 3: 创建图形语法,绘制柱状图
chart.interval().position('genre*sold');
// Step 4: 渲染图表
chart.render();
}
}
效果: