背景
本文使用 AntV 中的 g2 库,来绘制折线图和饼图。
官方最终效果如下:
本文从头开始,实现了其中基础部分。
初体验
建立 reactjs 框架
$ npx create-react-app my-g2-app
测试
$ cd my-g2-app $ npm start
可以在浏览器中打开默认页面
安装 g2 模块
$ npm install g2 --save $ npm install g2-react --save
浏览器页面创建容器
在 index.html
中,加入 root 容器。这时的 root 名称可以命名。
<div id="root"></div>
折线图
准备数据
下载文件 https://raw.githubusercontent.com/antvis/g2-react/master/examples/data.json
到本地。
编辑 js 文件
import createG2 from 'g2-react'; import { Stat } from 'g2'; import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import linedata from './data.json'; const Line = createG2(chart => { chart.line().position('time*price').color('name').shape('spline').size(2); chart.render(); }); class LineComponent extends Component { state = { data: linedata.slice(0, linedata.length / 2 - 1), width: 500, height: 250, plotCfg: { margin: [10, 100, 50, 120], }, } render() { return ( <div> <Line data={this.state.data} width={this.state.width} height={this.state.height} plotCfg={this.state.plotCfg} ref="myChart" /> </div> ); } } ReactDOM.render(<LineComponent />, document.getElementById('root'));
饼图
准备数据
下载文件 https://raw.githubusercontent.com/antvis/g2-react/master/examples/diamond.json
到本地。
编辑 js 文件
import createG2 from 'g2-react'; import { Stat } from 'g2'; import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import piedata from './diamond.json'; const Pie = createG2(chart => { chart.coord('theta'); chart.intervalStack().position(Stat.summary.proportion()).color('cut'); chart.render(); }); class PieComponent extends Component { state = { data: piedata.slice(0, piedata.length / 2 - 1), width: 500, height: 250, plotCfg: { margin: [10, 100, 50, 120], }, } render() { return ( <div> <Pie data={this.state.data} width={this.state.width} height={this.state.height} plotCfg={this.state.plotCfg} ref="myChart" /> </div> ); } } ReactDOM.render(<LineComponent />, document.getElementById('root'));
打包
$ npm run build
参考
- 在 react 组件中使用 G2
- g2-react 官方示例
- g2 simple-line 示例: G2 代码示例大全,可以找到各种用法。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于