本文将实现的功能如下:
- 通过api异步获取数据并动态加载
- 根据数值的区间,柱状图单根柱子颜色展示不同
- 柱状图横坐标标题过长,超出部分身略号代替
一、引入echart库和加载数据的api
import * as echarts from 'echarts';
import 'echarts/lib/chart/bar';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import { getCharList } from '../../../services/map/api';
二、处理数据,绘制柱状图
const drawChart = async() =>{
let chartOneXaxis = {} as any;
let chartOneYaxis = {} as any;
await getCharList().then((res: any) => {
chartOneXaxis = Object.keys(res.data.PENDING_ALARM)
chartOneYaxis = Object.values(res.data.PENDING_ALARM)
});
const chartDom1 = document.getElementById('linechart1')!;
const myChart1 = echarts.init(chartDom1);
myChart1.setOption({
title: { text: '此柱状图标题' },
tooltip: {},
xAxis: {
data: chartOneXaxis, //横坐标数据
axisLabel: {
show: true,
interval: 0,
rotate: 45,
fontSize: 10,
formatter: function (params: any) {
let val = '';
const show = 6;
if (params.length > show) {
val = params.substr(0, show) + '...';
return val;
} else {
return params;
}
},
},
},
yAxis: {
type: 'value',
},
series: [
{
name: '',
type: 'bar',
data: chartOneYaxis, //纵坐标数据
itemStyle: { //柱子颜色根据数值区间展示
normal: {
color: function (params: any) {
if(params.value > 0 && params.value < 10){
return "#FE8463";
}else if(params.value >= 10 && params.value <= 20 ){
return "#27727B";
}
return "#9BCA63";
},
},
},
},
],
});
}
api接口返回的数据格式如下:
{
"code": "",
"data": {
{"销售总量": 123423 },
{"销售总额": 103243524 },
},
"msg": "",
"success": true
}
可以通过Object.keys
、Object.values
分别将横坐标数值、纵坐标数值提取到两个不同的数组里,再进行数据渲染。
三、全部代码
import React, { useEffect } from 'react';
import * as echarts from 'echarts';
import 'echarts/lib/chart/bar';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import { getCharList } from '../../../services/map/api';
const LineChart: React.FC = () => {
const drawChart = async() =>{
let chartOneXaxis = {} as any;
let chartOneYaxis = {} as any;
await getCharList().then((res: any) => {
chartOneXaxis = Object.keys(res.data.PENDING_ALARM)
chartOneYaxis = Object.values(res.data.PENDING_ALARM)
});
const chartDom1 = document.getElementById('linechart1')!;
const myChart1 = echarts.init(chartDom1);
myChart1.setOption({
title: { text: '此柱状图标题' },
tooltip: {},
xAxis: {
data: chartOneXaxis,
axisLabel: {
show: true,
interval: 0,
rotate: 45,
fontSize: 10,
formatter: function (params: any) {
let val = '';
const show = 6;
if (params.length > show) {
val = params.substr(0, show) + '...';
return val;
} else {
return params;
}
},
},
},
yAxis: {
type: 'value',
},
series: [
{
name: '',
type: 'bar',
data: chartOneYaxis,
itemStyle: { //柱子颜色根据数值区间展示
normal: {
color: function (params: any) {
if(params.value > 0 && params.value < 10){
return "#FE8463";
}else if(params.value >= 10 && params.value <= 20 ){
return "#27727B";
}
return "#9BCA63";
},
},
},
},
],
});
}
useEffect(() => {
drawChart()
}, []);
return (
<div>
<div id="linechart1" style={{ height: 250 }}></div>
</div>
);
};
export default LineChart;