數據可視化在前端開發中經常會遇到,萬惡的圖表,有時候總是就差一點,可是怎么也搞不定。
別慌,咱們一起來研究。
引入我就不多說了 npm install echarts
對於基礎的可視化組件,我一般采用組件封裝的方式來使用echarts
當需要在項目中使用echarts做圖表時,可以直接將其封裝成一個組件
1 import React, { Component } from 'react';
2
3 // 引入 ECharts 主模塊
4 import echarts from 'echarts/lib/echarts';
5 // 引入環形圖
6 import 'echarts/lib/chart/pie';
7 // 引入提示框和標題組件
8 import 'echarts/lib/component/tooltip';
9 import 'echarts/lib/component/title';
10 import 'echarts/lib/component/visualMap';
11
12 export default class IndexPieData extends Component {
13 initCharts = () => {
14 const data = this.props.data;
15 var piedata = data.map((item, index) => {
16 return {
17 value: item.y, //value和name是echarts規定的,嗚嗚嗚
18 name: item.x,
19 };
20 });
21 // 基於准備好的dom,初始化echarts實例
22 var myChart = echarts.init(document.getElementById('main'));
23 // 繪制圖表
24 myChart.setOption({
25 tooltip: {
26 trigger: 'item',
27 // formatter: "{a} <br/>{b}: {c} ({d}%)"
28 formatter: '{b}: {d}%',
29 },
30 series: [
31 {
32 name: '設備占比數量',
33 type: 'pie',
34 radius: ['50%', '60%'],
35 label: {
36 formatter: '{b}:{d}%',
37 textStyle: {
38 color: '#000000',
39 fontSize: 12,
40 },
41 },
42 data: piedata,
43 },
44 });
45 };
46
47 componentDidMount() {
48 this.initCharts();
49 }
50 componentDidUpdate() { //當圖表切換的時候,重新執行
51 this.initCharts();
52 }
53 render() {
54 return <div id="main" style={{ width: '100%', height: 311 }} />;
55 }
56 }
//在需要使用的頁面 引入並使用
import IndexPieData from '../';
<IndexPieData data={pieData} height={300}></IndexPieData>
echarts一些常用的配置項
toolbox工具欄 toolbox: { show: true, //默認為true
itemSize: 15, //工具欄圖標的大小 default: 15
feature: { //自定義工具按鈕,添加其他的
saveAsImage: { show: true }, //保存為圖片
magicType: { type: ['bar','line'] //設置柱狀圖,折線圖切換
}, dataZoom: { show: true, yAxisIndex: false //禁止y軸做區域縮放
}, restore: { //添加配置項還原圖標工具
show: true } } } yAxis: { type: 'value', axisLabel: { formatter: function (val) { return val; }, showMinLabel: true, showMaxLabel: true, } } //type的值 //value 數值軸,適用於連續數據 //category 類目軸,適用於離散的類目數據,需要設置data //time 時間軸 適用於連續的時序數據 //log 對數軸,適用於對數數據
tooltip:{ //提示框組件
trigger: 'item', //數據項圖形出發
formatter: '{b}: {d}%', //設置提示框內容
}
。。。太多了,用的時候再看吧!
最近一直在使用antd pro進行項目開發,在引入echarts時,一般都是配合表單查詢進行使用
在實際開發中
//同樣對echarts代碼進行封裝
daysAlertChart.js
// 引入 ECharts 主模塊
import echarts from 'echarts/lib/echarts';
import moment from 'moment';
import { formatMessage, FormattedMessage } from 'umi/locale';
const typeList = ['red_alert', 'yellow_alert', 'offline', 'expired', 'suspicious', 'sample_placement_error', 'sample_expired', 'sample_inventory', 'task_incomplete',];
export function daysAlertChart(chartData) {
let dataList = [];
let currentSubtext = [];
let dateTime = [];
chartData.alertDailyMap.forEach((item, idx) => {
let alertType = item.alertType;
console.log(alertType)
alertType = typeList.indexOf(alertType) > -1 ? formatMessage({ id: `app.alert.${alertType}` }) : alertType;
currentSubtext.push({
name: alertType
})
dataList.push({
name: alertType,
data: chartData.alertDailyMap[idx].alertCount,
type: 'bar'
})
console.log(dataList)
});
chartData.time.forEach((item2, idx2) => {
dateTime.push(
moment(item2).format('YYYY-MM-DD'),
)
});
let option = {
color: ['#f5222d', '#faad14', '#d9d9d9', '#1890ff', '#4d4dff', '#32cd99'],
tooltip: {
show: true,
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
legend: {
width: 1200,
//left:'30%',
bottom: '0%',
data: currentSubtext,
formatter: val => {
return typeList.indexOf(val) > -1
? formatMessage({ id: `app.alert.${val}` })
: val
}
},
toolbox: {
show: true,
right: 5,
top: 10,
feature: {
magicType: { show: true, type: ['bar', 'line'] }, //實現柱狀圖和折線圖的切換
dataZoom: {
show: true,
yAxisIndex: false
},
restore: { show: true },
saveAsImage: { show: true }
}
},
grid: {
left: '4%',
right: '4%',
bottom: '5%',
containLabel: true
},
xAxis: {
type: 'category',
data: dateTime,
},
yAxis: {
type: 'value',
axisLabel: {
formatter: function (val) {
return val;
},
showMinLabel: true,
showMaxLabel: true,
},
},
series: dataList
};
return option;
}
因為antd pro項目采用dva完成對fetch請求的封裝,可以在完成數據請求之后的回調中進行echarts圖表的初始化
//在頁面代碼中
import {echartsDemo} from '../';
// 引入 ECharts 主模塊
import echarts from 'echarts/lib/echarts';
// 引入圖表組件
import 'echarts/lib/chart/line';
import 'echarts/lib/chart/bar';
// 引入提示框和標題組件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/toolbox';
import 'echarts/lib/component/grid';
import 'echarts/lib/component/dataZoom';
return (
<div id={'daysAlert'} style={{width:'100%', height:'500px'}}></div>
)
function initChart(domId,data,func) {
let dom = document.getElementById(domId);
if (dom) {
let myChart = echarts.init(dom);
let option = func(data);
myChart.setOption(option,true);
}
}
componentDidMount() {
this.props.dispatch({
type: 'statistics/fetchAlertCountData',
payload: {
startTime: startTime,
endTime: endTime
},
//callback需要在對應的models請求接口時,進行傳參callback
//並設置 if(callback) callback(res.data)
callback: (alertData)=>{ initChart('daysAlert',alertData,daysAlertChart)}
})
}
///OK!!!