Recently Ali official open source Bizcharts Chart library based on the react technology stack, each of the chart items are in the form of components, close to the use of react features. At the same time Bizcharts is encapsulated based on G2, Bizcharts also inherits G2-related features. The company is currently using the Echarts Chart Library, and the following will analyze the 3 chart libraries.
Bizcharts
Document Address: Bizcharts
1, installation
Introduced through Npm/yarn
npm install bizcharts --saveyarn add bizcharts --save
2. references
After the successful installation is complete, you can use import or require to reference it.
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>
In this example, the data configuration of the chart is stored separately in other JS files to avoid the page being too jumbled.
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 the metric
Cols : {
Sold: { alias: ‘Sales ‘ }, // Data Field Alias Mapping
Genre: { alias: ‘game kind ‘ }
},
Title : {
autoRotate: true, // whether automatic rotation is required, the default is true
textStyle: {
fontSize: ‘12’,
textAlign: ‘center’,
Fill: ‘#999‘,
fontWeight: ‘bold‘,
Rotate: 30
}, // Axis text property configuration
Position: ‘center’, // title location, **new**
}
}
Effect preview:
3, DataSet
The data of the icon can be processed by the dataset (Data Processing module) in Bizcharts, which inherits from the G2 and is analyzed in detail later in this article.
Quick Jump
G2
Bizcharts was developed based on G2, and G2 was also practiced in the process of studying bizcharts.
First, installation
As with Bizcharts, it can be introduced through Npm/yarn
npm install @antv/g2 --saveyarn add @antv/g2 --save
Unlike Bizcharts, G2 initialization data is not introduced as a component, but rather requires getting the diagram to be initialized under a DOM. Gets the unique property ID of the DOM, initialized by the chart ().
Second. references
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 width of the chart
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;
Third, DataSet
The dataset has two main functions, parsing data (Connector) & Processing data (Transform).
The Official document description is more detailed, can refer to the official website classification:
parse the source data, turn CSV, Dsv,geojson into standard JSON, view connector
Processing data, including filter,map,fold (fill data) and other operations, view transform
Statistical functions, summary statistics, percentages, boxes and other statistical functions, view Transform
Special data processing, including geographic data, rectangular tree, Sankitu, text cloud data processing, view Transform
// step1 creates a dataset specifying the state quantity
Const ds = new DataSet({
State: {
Year: ‘2010’
}
});
// step2 creates a DataView
Const dv = ds.createView().source(data);
Dv.transform({
Type: ‘filter’,
Callback(row) {
Return row.year === ds.state.year;
}
});
// step3 references DataView
Chart.source(dv);
// step4 update state quantity
ds.setState(‘year‘, ‘2012’);
The following examples are analyzed using the official website documentation
Example One
The data in this form is the number of people of different age groups in the United States, and tabular data is stored in CVS-type files.
Data Link (JSON-type data in the link)
State
|
less than 5 years old |
5-13 years old |
14-17 years old |
18-24 years old |
25-44 years old |
45-64 years old |
65 years old 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 |
... |
... |
... |
... |
... |
... |
... |
... |
Initializing the data processing module
Import DataSet from ‘@antv/data-set‘;
Const ds = new DataSet({
//state indicates the state quantity of the created dataSet, you can not set it
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‘, // Load data using CSV type Connector. If it is json type data, you can not set it. The default is json type.
});
/**
Trnasform processing data, you can set the processing type by type, refer to the above api document
The processed data format is
[
{state:‘WY‘,key:‘less than 5 years old’, value:38253},
{state:‘WY‘,key:‘5 to 13 years old’, value: 60890},
]
*/
dvForAll.transform({
Type: ‘fold’,
Fields: [ 'less than 5 years old', '5 to 13 years old', '14 to 17 years old', '18 to 24 years old', '25 to 44 years old', '45 to 64 years old', '65 years old and older' ],
Key: ‘age’,
Value: ‘population‘
});
//The rest of the transform operation
Const dvForOneState = ds
.createView(‘populationOfOneState‘)
.source(dvForAll); // Inherit from full data, the word can also be .source(‘populationByAge‘)
dvForOneState
.transform({ // Filter data to filter out the region data that the state matches
Type: ‘filter’,
Callback(row) {
Return row.state === ds.state.currentState;
}
})
.transform({
Type: ‘percent‘,
Field: ‘population‘,
Dimension: ‘age’,
As: ‘percent‘
});
Drawing with G2
G2-chart API documentation
Import G2 from ‘@antv/g2‘;
// Initialize the chart, id specifies the dom to be inserted in the chart, and other properties set the width and height of the chart.
Const c1 = new G2.Chart({
Id: ‘c1‘,
forceFit: true,
Height: 400,
});
// chart initializes the processed data dvForAll
C1.source(dvForAll);
// Configure the chart legend
C1.legend({
Position: ‘top‘,
});
/ / Set the axis configuration, the method returns a chart object, the following code represents the data of the axis attribute for the population, converted to data in M units
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, trigger the event, modify the state state of the ds, once the state quantity changes, it will trigger the update of the chart, so the c2 pie chart will trigger the change
C1.on(‘tooltip:change‘, function(evt) {
Const items = evt.items || [];
If (items[0]) {
/ / Modified currentState is the area of the tooltip touched by the mouse
ds.setState(‘currentState‘, items[0].title);
}
});
// draw a 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 size of the pie chart
});
C2.legend(false);
c2.intervalStack()
.position(‘percent‘)
.color(‘age‘)
.label(‘age*percent‘,function(age, percent) {
Percent = (percent * 100).toFixed(2) + ‘%‘;
Return age + ‘ ‘ + percent;
});
C1.render();
C2.render();
Echarts
Echarts is a mature chart library, easy to use, many types of charts, easy to get started. Document resources are also rich, do not repeat here.
Echarts Documentation
Echarts & Bizcharts & G2 Contrast
Comparing the Bizcharts and G2 two chart libraries, the bizcharts is primarily a one-layer package that allows the diagram to be called in the form of components, loading on demand, and making it easier to use.
A simple comparison of the differences between the three chart libraries:
Initialize the chart:
Echarts:
// Initialize the ECharts instance based on the prepared dom
var myChart = echarts.init(document.getElementById(‘main‘));
Bizcharts:
// in the form of a component, combined call
import { Chart, Geom, Axis, ... } from ‘bizcharts‘;
<Chart width={600} height={400} data={data}>
...
</Chart>
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 width of the chart
Height: 300 // specify the height of the chart
});
chart.source(data);
chart.render();
<div id="c1" className="charts"></div>
Configuration:
Echarts:
// Focus on options for configuration
myChart.setOption({
Title: {
...
},
Tooltip: {},
xAxis: {
Data: [...]
},
yAxis: {},
Series: [{
...
}]
});
Bizcharts:
/ / According to the needs of the component, after the configuration parameters are assigned
const cols = {...};
const data = {...};
<Chart width={600} height={400} data={data} sca`enter code here`le={cols}>
...
</Chart>
G2:
Chart.tooltip({
triggerOn: ‘...‘
showTitle: {boolean}, // whether to show title, the default is true
Crosshairs: {
...
Style: {
...
}
}
});
Event:
Echarts: Event API documentation
myChart.on(‘click‘, function (params) {
console.log(params);
});
Bizcharts: Event API documentation
<chart onEvent={e =>
<chart
onEvent={e => {
//do something
}}
/>
{ //do something }}/>
G2: Event API documentation
chart.on(‘mousedown‘, ev => {});
Summarize
Compared with the above 3 charts, Echarts and bizcharts are relatively easy to use, especially the Echarts configuration is very clear, bizcharts and there are some similarities. The Bizcharts advantage is that the modular form makes the DOM structure relatively clear, on-demand referencing. G2 is more suitable for referencing when a large number of chart interactions are required, and its rich API handles interactive logic in a relatively advantageous position.
Advertised
This article is published in the Mint Front-end weekly, welcome Watch & Star★, reproduced please indicate the source.
Welcome to the discussion, please go again????? ~
Three Big chart libraries: Echarts, Bizcharts and G2, how do I choose?