Recently, The official open source BizCharts library of Alibaba is based on React technology stack, and each chart item adopts the form of component, which is close to the use characteristics of React. Meanwhile, BizCharts is encapsulated based on G2, and BizCharts also inherits related features of G2. The company currently uses the ECharts chart library. The following will analyze and compare the three chart libraries.

BizCharts

Documentation address: BizCharts

A, install,

Import through NPM/YARN

    npm install bizcharts --save

    yarn add bizcharts  --save
Copy the code

Second, the reference

After a successful installation, you can reference it using import or require.

Example:

    import { Chart, Geom, Axis, Tooltip, Legend } from 'bizcharts';
    import chartConfig from './assets/js/chartConfig';
    
    <div className="App">
	    <Chart width={600} height={400} data={chartConfig.chartData} scale={chartConfig.cols}>
          <Axis name="genre" title={chartConfig.title}/>
          <Axis name="sold" title={chartConfig.title}/>
          <Legend position="top" dy={-20} />
          <Tooltip />
          <Geom type="interval" position="genre*sold" color="genre" />
        </Chart>
    </div>
Copy the code

In this example, the data configuration of the chart is stored separately in other JS files to avoid too much clutter on the page

    module.exports = {
	    chartData: [{genre: 'Sports'.sold: 275.income: 2300 },
		    { genre: 'Strategy'.sold: 115.income: 667 },
		    { genre: 'Action'.sold: 120.income: 982 },
		    { genre: 'Shooter'.sold: 350.income: 5271 },
		    { genre: 'Other'.sold: 150.income: 3710}].// Define metrics
	    cols : {
		    sold: { alias: 'Sales volume' }, // Data field alias mapping
		    genre: { alias: 'Game Type'}},title : {
		    autoRotate: true.// Whether automatic rotation is required. Default is true
		    textStyle: {
		      fontSize: '12'.textAlign: 'center'.fill: '# 999'.fontWeight: 'bold'.rotate: 30
		    }, // Axis text attribute configuration
		    position:'center'.// Title position, ** add **}}Copy the code

Effect preview:

Third, the DataSet

The icon data can be processed by dataset(data processing module) in BizCharts, which is inherited from G2 and will be analyzed in detail in the following.

Quick jump


G2

BizCharts was developed based on G2, and we also practiced G2 together in the process of BizCharts research.

A, install,

Like BizCharts, it can be imported via NPM/YARN

    npm install @antv/g2 --save

    yarn add @antv/g2 --save
Copy the code

Unlike BizCharts, G2 initialization data is not imported as a component, but rather a chart that needs to be initialized under a DOM. After obtaining the UNIQUE attribute ID of the DOM, it is initialized using chart().

Example:

    import React from 'react';
    import G2 from '@antv/g2';
	  class g2 extends React.Component {constructor(props) {
	    super(props);
	    this.state = {
	      data :[
	        { genre: 'Sports'.sold: 275 },
	        { genre: 'Strategy'.sold: 115 },
	        { genre: 'Action'.sold: 120 },
	        { genre: 'Shooter'.sold: 350 },
	        { genre: 'Other'.sold: 150}}; } componentDidMount() {const chart = new G2.Chart({
    	      container: 'c1'.// Specify the chart container ID
    	      width: 600.// Specify the chart width
    	      height: 300 // Specify the height of the chart
    	    });
    	    chart.source(this.state.data);	
    	    chart.interval().position('genre*sold').color('genre');	    
    	    chart.render();
            }
	    render() {
	        return (
	            <div id="c1" className="charts"></div>); }}export default g2;
Copy the code

Effect:

Third, the DataSet

DataSet mainly has two functions: Connector parsing and Transform.

The official documentation is more detailed, please refer to the classification on the official website:

Analyze the source data, convert CSV, DSV, geoJSON into standard JSON, view the processing data of Connector, including filter,map,fold and other operations, view the Transform statistical function, summary statistics, percentage, sealing and other statistical functions, See Transform for special data processing, including data processing for geographic data, rectangular tree graphs, Sankey graphs, and word clouds. See Transform

    // step1 Create dataset specify state quantity
    const ds = new DataSet({
     state: {
	    year: '2010'}});// step2 create DataView
    const dv = ds.createView().source(data);
    
    dv.transform({
     type: 'filter',
     callback(row) {
		returnrow.year === ds.state.year; }});// step3 refer to DataView
    chart.source(dv);
    // step4 update the status
    ds.setState('year'.'2012');
Copy the code

The following uses the example provided by the official website for analysis

The sample a

The data in this table is the population of different age groups in each STATE of the United States. The table data is stored in a CVS file. Data link (The link is json data)

State Less than 5 years old 5 to 13 14 to 17 years Aged 18 to 24 25 to 44 45 to 64 years old Age 65 and above
WY 38253 60890 29314 53980 137338 147279 65614
DC 36352 50439 25225 75569 193557 140043 70648
VT 32635 62538 33757 61679 155419 188593 86649
. . . . . . . .

Initialize the data processing module

    import DataSet from '@antv/data-set';
 
    const ds = new DataSet({
    //state indicates the state amount of the dataSet to be created
     state: {
	    currentState: 'WY'}});const dvForAll = ds
    // Create a data view named populationByAge under the DataSet instance
	    .createView('populationByAge') 
	// source initializes the chart data. Data can be the data result returned by the HTTP request
	    .source(data, {
	      type: 'csv'.// Use the CSV Connector to load data. If the data type is JSON, you do not need to set it to JSON by default
    });
    
    [{state:'WY',key:' less than 5 years old ', '< 5 years old ',' < 5 years old ', '< 5 years old ',' < 5 years old ', '< 5 years old' Value: 38253}, {state: 'WY, key:' 5 to 13 years old, the value: 60890},] * / 
    dvForAll.transform({
	    type: 'fold'.fields: [ 'Under 5'.'Ages 5 to 13'.'14 to 17 '.'18 to 24 '.'25 to 44 '.'45 to 64 '.'65 and over '].key: 'age'.value: 'population'
    });
    
    // The remaining transform operations
    const dvForOneState = ds
	    .createView('populationOfOneState')
	    .source(dvForAll); // Inherit from full data. Source ('populationByAge')
     dvForOneState
	     .transform({ // Filter data to filter out the region data matching state
	    type: 'filter',
	    callback(row) {
	      return row.state === ds.state.currentState;
	    }
    })
     .transform({
	    type: 'percent'.field: 'population'.dimension: 'age'.as: 'percent'
	    });
Copy the code

Use G2 to plot g2-chart Api documents

import G2 from '@antv/g2';

// Initialize the chart. The id specifies the DOM into which the chart is to be inserted, and the other properties set the width and height of the chart
const c1 = new G2.Chart({
  id: 'c1'.forceFit: true.height: 400});// chart initializes processed data dvForAll
c1.source(dvForAll);

// Configure diagram legend
c1.legend({
  position: 'top'});// Set the axis configuration. This method returns the chart object. The following code shows how to convert the data whose axis attribute is population into M
c1.axis('population', {
  label: {
    formatter: val= > {
      return val / 1000000 + 'M'; }}}); c1.intervalStack() .position('state*population')
  .color('age')
  .select(true, {
    mode: 'single'.style: {
      stroke: 'red'.strokeWidth: 5}});When the tooltip changes, events are triggered to change the ds state. When the ds state changes, chart updates are triggered, so the C2 pie chart changes
c1.on('tooltip:change'.function(evt) {
  const items = evt.items || [];
  if (items[0]) {
  // Change currentState to the location of the tooltip touched by the mouse
    ds.setState('currentState', items[0].title); }});// Draw the pie chart
const c2 = new G2.Chart({
  id: 'c2'.forceFit: true.height: 300.padding: 0}); c2.source(dvForOneState); c2.coord('theta', {
  radius: 0.8 // Set the pie chart size
});
c2.legend(false);
c2.intervalStack()
  .position('percent')
  .color('age')
  .label('age*percent'.function(age, percent) {
    percent = (percent * 100).toFixed(2) + The '%';
    return age + ' ' + percent;
  });

c1.render();
c2.render();
Copy the code

ECharts

ECharts is a mature chart library that is easy to use, has a wide variety of charts, and is easy to use. The documentation resources are also relatively rich, so I will not repeat them here. ECharts document


ECharts & BizCharts & G2 comparison

Comparing BizCharts with G2, BizCharts is mainly packaged so that charts can be called as components and loaded on demand, making it easier to use. A quick comparison of the differences between the three chart libraries:

Initialization diagram: ECharts:

// Initializes the ECharts instance based on the prepared DOM
var myChart = echarts.init(document.getElementById('main'));
Copy the code

BizCharts:

// Composite calls in the form of components
import { Chart, Geom, Axis, ... } from 'bizcharts';

<Chart width={600} height={400} data={data}>.</Chart>
Copy the code

G2:

// Based on the prepared DOM, initialize after configuration
const chart = new G2.Chart({
    container: 'c1'.// Specify the chart container ID
    width: 600.// Specify the chart width
    height: 300 // Specify the height of the chart
});
chart.source(data);
chart.render();
 
<div id="c1" className="charts"></div>
Copy the code

Configuration:

ECharts:

// Focus on configuration in options
myChart.setOption({
    title: {... },tooltip: {},
    xAxis: {
        data: [...]. },yAxis: {},
    series: [{...}]});Copy the code

BizCharts:

// Assign parameters according to component requirements
constcols = {... };constdata = {... };<Chart width={600} height={400} data={data} sca`enter code here`le={cols}>.</Chart>

Copy the code

G2:

chart.tooltip({
  triggerOn: '... '
  showTitle: {boolean}, // Whether to display title. Default is truecrosshairs: { ... style: { ... }}});Copy the code

Events:

ECharts: Event API documentation

myChart.on('click'.function (params) {
    console.log(params);
});
Copy the code

BizCharts: Event API documentation

<chart
  onEvent={e => {
    //do something}} / >Copy the code

G2: Event API document

chart.on('mousedown', ev => {});
Copy the code

conclusion

Compared to the above three charts, ECharts and BizCharts are relatively easy to use, especially ECharts configuration is very clear, BizCharts also has some similarities. The advantage of BizCharts is that the componentized form makes the DOM structure relatively clear and can be referenced on demand. G2 is suitable for reference when a large number of chart interactions are required, and its rich API handling interaction logic is relatively advantageous.