在开发中,我们会遇到需要在前端显示图表的业务需求。在本文中将介绍如何使用echart插件绘制业务需求的图表,包括:“绘制饼状图”、“绘制折线图”、“绘制柱状图”。
1、绘制饼状图。
前端HTML代码:
Js请求后端代码:
//销售大类数据绘图
function salesPie (date1, date2, shopID) {
var categoryParentNameArr = [];
var message = new Array();
$.ajax({
url: retailTrade_url,
type: mothod_post,
async: true,
dataType: "json",
data: { "datetimeStart": date1, "datetimeEnd": date2, "shopID": shopID },
success: function succFunction (data) {
console.log(data);
if (data.ERROR == "EC_NoError") {
if (data.reportList.length > 0) {
for (var i = 0; i < data.reportList.length; i++) {
var totalAmountSummaryarr = {};
categoryParentNameArr[i] = data.reportList[i].totalAmountSummary.toFixed(2) < 0 ? data.reportList[i].categoryParentName + "(退货)" : data.reportList[i].categoryParentName;;
totalAmountSummaryarr["value"] = data.reportList[i].totalAmountSummary.toFixed(2) < 0 ? Math.abs(data.reportList[i].totalAmountSummary.toFixed(2)) : data.reportList[i].totalAmountSummary.toFixed(2);
totalAmountSummaryarr["name"] = data.reportList[i].totalAmountSummary.toFixed(2) < 0 ? data.reportList[i].categoryParentName + "(退货)" : data.reportList[i].categoryParentName;
message.push(totalAmountSummaryarr);
}
$(".noData").remove();
//绘图
pie(categoryParentNameArr, message);
} else {
$(".noData").remove();
pie(categoryParentNameArr, message);
$("#pie").append("
暂时无销售数据");
}
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
layer.msg("服务器错误");
}
})
}
首先声明两个数组变量:
var categoryParentNameArr = [];
var message = new Array();
然后请求服务器后端,返回数据,例如返回数据如下:
遍历后端返回的数据,将分类名称放到categoryParentNameArr数组。声明一个对象totalAmountSummaryarr,对象的value存储总额,对象的name存储分类名称。然后将对象totalAmountSummaryarr放到message数组中。
遍历完成后,调用pie函数,传入categoryParentNameArr和message数组作为参数:
pie(categoryParentNameArr, message);
//饼图
function pie (categoryParentNameArr, totalAmountSummaryarr) {
var myChart = echarts.init($('#pie').get(0))
// 指定图表的配置项和数据
option = {
title: {
text: '销售汇总',
x: 'left'
},
tooltip: {
trigger: 'item',
formatter: "{a}
{b} : {c} ({d}%)"
},
legend: {
type: 'scroll',
orient: 'vertical',
right: 0,
top: 50,
bottom: 20,
data: categoryParentNameArr,
zlevel: 0,
},
series: [
{
name: '销售大类占比',
type: 'pie',
radius: '60%',
center: ['40%', '60%'],
data: totalAmountSummaryarr,
zlevel: 1,
itemStyle: {
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
},
label: {//将数量与百分比一起显示
show: true
// normal: {
// formatter: '{b}:{c}: ({d}%)',
// textStyle: {
// fontWeight: 'normal',
// fontSize: 15
// }
// }
},
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
}
初始化echart和配置图表option:
var myChart = echarts.init($('#pie').get(0))
// 指定图表的配置项和数据
option =
……
设置标题title、提示框tooltip、自定义文本说明legend、数据绑定series,显示图表:
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
效果图如下:
2、绘制折线图。
前端HTML代码:
2019-02-18日近七天销售走势
JS请求后端代码:
function yeardate (date1, date2, shopID) {
var totalAmountArrar = new Array();
var totalGrossArrar = new Array();
var sum = 0;
$.ajax({
url: MonthlyReportSummary_URL,
type: mothod_post,
async: true,
dataType: "json",
data: { "datetimeStart": date1, "datetimeEnd": date2, "shopID": shopID },
success: function succFunction (data) {
console.log(data);
//渲染绘图数据
if (data['reportList'].length != 0) {
for (var i = 1; i <= 12; i++) {
$.each(data['reportList'], function (j, val) {
if (i == val['dateTime'].substring(5, 7)) {
totalAmountArrar[sum] = val['totalAmount'].toFixed(2);
totalGrossArrar[sum] = val['totalGross'].toFixed(2);
return false;
} else {
totalAmountArrar[sum] = "0.00";
totalGrossArrar[sum] = "0.00";
}
});
sum++;
}
sketch(monthArrar, totalAmountArrar, totalGrossArrar);//绘图
sum = 0;
} else {
for (var i = 1; i <= 12; i++) {
monthArrar[sum] = i + "月";
totalAmountArrar[sum] = "0.00";
totalGrossArrar[sum] = "0.00";
sum++;
}
sketch(monthArrar, totalAmountArrar, totalGrossArrar);//绘图
sum = 0;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
layer.msg("服务器错误");
}
})
}
声明两个数组:
var totalAmountArrar = new Array();
var totalGrossArrar = new Array();
然后请求服务器后端,返回数据,例如返回数据如下:
遍历返回的数据,totalAmountArrar数组存放销售额,totalGrossArrar数组存放毛利率:
for (var i = 1; i <= 12; i++) {
$.each(data['reportList'], function (j, val) {
if (i == val['dateTime'].substring(5, 7)) {
totalAmountArrar[sum] = val['totalAmount'].toFixed(2);
totalGrossArrar[sum] = val['totalGross'].toFixed(2);
return false;
} else {
totalAmountArrar[sum] = "0.00";
totalGrossArrar[sum] = "0.00";
}
});
sum++;
}
遍历完后,调用sketch函数:
sketch(monthArrar, totalAmountArrar, totalGrossArrar);//绘图
monthArrar为常量:
const monthArrar = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];|
sketch函数,使用echart绘制折线图:
//业绩图
function sketch (arr, arr1, arr2) {
var myChart = echarts.init($('#sell').get(0))
// 指定图表的配置项和数据
var trendsoption = {
title: {
},
tooltip: {},
grid: {//控制图表大小
left: '4%',
right: '4%',
bottom: '3%',
containLabel: true
},
legend: {
data: ['销量额', '销售毛利'],
y: 'top',
icon: "circle"
},
xAxis: {
data: arr
},
yAxis: {},
series: [{
name: '销量额',
type: 'line',
label: {
normal: {
show: true,
position: 'top'
}
},
data: arr1
},
{
name: '销售毛利',
type: 'line',
label: {
normal: {
show: true,
position: 'top'
}
},
data: arr2
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(trendsoption);
}
效果图如下:
3、绘制柱状图。
前端HTML代码:
JS请求后端代码:
//销售人员的业绩绘图
function salesPerformanceOfSalesStaff (date1, date2, shopID) {
var staffName = [];
var totalAmount = [];
var NO = [];
var grossMargin = [];
$.ajax({
url: retailTradeDailyReportByStaff_url,
type: mothod_post,
async: true,
dataType: "json",
data: { "datetimeStart": date1, "datetimeEnd": date2, "shopID": shopID },
success: function succFunction (data) {
console.log(data);
if (data.ERROR == "EC_NoError") {
if (data.retailTradeDailyReportByStaff.length > 0) {
for (var i = 0; i < data.retailTradeDailyReportByStaff.length; i++) {
staffName[i] = data.retailTradeDailyReportByStaff[i].staffName;
totalAmount[i] = data.retailTradeDailyReportByStaff[i].totalAmount.toFixed(2);
NO[i] = data.retailTradeDailyReportByStaff[i].NO;
grossMargin[i] = data.retailTradeDailyReportByStaff[i].grossMargin.toFixed(2);
}
$(".performance").remove();
results(staffName, totalAmount, NO, grossMargin);
} else {
$(".performance").remove();
results(staffName, totalAmount, NO, grossMargin);
$("#salesPerformance").append("
暂无销售业绩");
}
} else {
if (data.msg == "" || data.msg) {
layer.msg(服务器错误);
} else {
layer.msg(data.msg);
}
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
layer.msg("服务器错误");
}
})
}
声明了四个数组:
var staffName = [];
var totalAmount = [];
var NO = [];
var grossMargin = [];
然后请求服务器后端,返回数据,例如返回数据如下:
遍历返回的数据,staffName数组存员工名称,totalAmount数组存放销售额,NO数组存放销售笔数、grossMargin数组存放销售毛利:
for (var i = 0; i < data.retailTradeDailyReportByStaff.length; i++) {
staffName[i] = data.retailTradeDailyReportByStaff[i].staffName;
totalAmount[i] = data.retailTradeDailyReportByStaff[i].totalAmount.toFixed(2);
NO[i] = data.retailTradeDailyReportByStaff[i].NO;
grossMargin[i] = data.retailTradeDailyReportByStaff[i].grossMargin.toFixed(2);
}
遍历完成后,调用results函数:
results(staffName, totalAmount, NO, grossMargin);
result函数,使用echart绘制柱状图:
//销售人员业绩图
function results (staffName, totalAmount, NO, grossMargin) {
var myChart = echarts.init($('#salesPerformance').get(0))
// 指定图表的配置项和数据
var posList = [
'left', 'right', 'top', 'bottom',
'inside',
'insideTop', 'insideLeft', 'insideRight', 'insideBottom',
'insideTopLeft', 'insideTopRight', 'insideBottomLeft', 'insideBottomRight'
];
myChart.configParameters = {
rotate: {
min: -90,
max: 90
},
align: {
options: {
left: 'left',
center: 'center',
right: 'right'
}
},
verticalAlign: {
options: {
top: 'top',
middle: 'middle',
bottom: 'bottom'
}
},
position: {
options: echarts.util.reduce(posList, function (map, pos) {
map[pos] = pos;
return map;
}, {})
},
distance: {
min: 0,
max: 100
}
};
myChart.config = {
rotate: 90,
align: 'left',
verticalAlign: 'middle',
position: 'insideBottom',
distance: 15,
onChange: function () {
var labelOption = {
normal: {
rotate: app.config.rotate,
align: app.config.align,
verticalAlign: app.config.verticalAlign,
position: app.config.position,
distance: app.config.distance
}
};
myChart.setOption({
series: [{
label: labelOption
}, {
label: labelOption
}, {
label: labelOption
}, {
label: labelOption
}]
});
}
};
var labelOption = {
normal: {
show: true,
position: myChart.config.position,
distance: myChart.config.distance,
align: myChart.config.align,
verticalAlign: myChart.config.verticalAlign,
rotate: myChart.config.rotate,
formatter: '{c} {name|{a}}',
fontSize: 14,
rich: {
name: {
textBorderColor: '#fff'
}
}
}
};
option = {
title: {
text: '销售业绩对比图',
x: 'left'
},
color: ['#003366', '#006699', '#4cabce'],
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {//控制图表大小
left: '2%',
right: '2%',
bottom: '1%',
containLabel: true
},
legend: {
data: ['销售总额', '销售毛利', '销售笔数']
},
// toolbox: {
// show: true,
// orient: 'vertical',
// left: 'right',
// top: 'center',
// feature: {
// mark: { show: true },
// dataView: { show: true, readOnly: false },
// magicType: { show: true, type: ['line', 'bar', 'stack', 'tiled'] },
// restore: { show: true },
// saveAsImage: { show: true }
// }
// },
calculable: true,
xAxis: [
{
type: 'category',
axisTick: { show: false },
data: staffName,
axisPointer: {
type: "shadow"
}
}
],
yAxis: [
{
type: 'value',
name: '销售金额',
min: 0,
max: function (value) {
return value.max;
},
axisLabel: {
formatter: '{value}'
},
nameLocation: 'center',
nameGap: 50,
splitLine: { show: false },
axisLine: {
lineStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [{
offset: 0, color: '#003366' // 0% 处的颜色
}, {
offset: 1, color: '#4cabce' // 100% 处的颜色
}],
global: false // 缺省为 false
}
}
}
},
{
type: 'value',
name: '销售笔数',
min: 0,
max: function (value) {
return value.max;
},
axisLabel: {
formatter: '{value}'
},
nameLocation: 'center',
nameGap: 30,
nameRotate: -90,
nameTextStyle: {
color: "#4cabce"
},
splitLine: { show: false },
axisLine: {
lineStyle: {
color: "#4cabce"
}
}
}
],
series: [
{
name: '销售总额',
type: 'bar',
barGap: 0,
barWidth: 30,
label: labelOption,
data: totalAmount
},
{
name: '销售毛利',
type: 'bar',
barWidth: 30,
label: labelOption,
data: grossMargin
},
{
name: '销售笔数',
type: 'bar',
barWidth: 30,
label: labelOption,
data: NO,
yAxisIndex: 1,
}
]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
}
效果图如下: