【一】前端小白的小案例练习之Echarts

2018-06-23  本文已影响0人  吴里庆庆

1极坐标下的堆叠柱状图

app.title = '极坐标系下的堆叠柱状图';

option = {
    angleAxis: {
    },
    radiusAxis: {
        type: 'category',
        data: ['达标情况', '', '', ''],
        z: 10
    },
    polar: {
    },
    series: [{
        type: 'bar',
        data: [0, 0, 0, 0],
        coordinateSystem: 'polar',
        name: 'A',
        stack: 'a',
       // color:'red'
    }, {
        type: 'bar',
        data: [0,0, 0, 0.08],
        coordinateSystem: 'polar',
        name: 'B',
        stack: 'a',
        color:'transparent'
    }, {
        type: 'bar',
        data: [0, 0, 0, 0.92],
        coordinateSystem: 'polar',
        name: 'C',
        stack: 'a'
    }],
    legend: {
        show: false,
        data: ['A', 'B', 'C']
    }
};

效果图如下:


图1.1 极坐标下的堆叠柱状图.png

2 环形图

app.title = '环形图';

option = {
    tooltip: {
        show:false,
        trigger: 'item',
        formatter: "{a} <br/>{b}: {c} ({d}%)"
    },
    
    series: [
        {
            name:'工单数',
            type:'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: true,
            label: {
                normal: {
                    show: false,
                    position: 'center'
                }
            },
            data:[
                {value:0.9, name:'有效'},
                {value:0.1, name:'无效'}
               
            ],
            color:['#87CEEB', 'transparent']  ,
       animation: false
        }
    ]
};

animation: false 取消动画效果

效果图:


2.1 环形图效果图.png

3 实战演练

3.1 饼图

功能描述:显示饼图信息,点击能钻取到第二层(这里的第二层实则还是一层只是数据动态修改了)

function getEchartsPie(pieData, userPoint, billYear, billMonth, regionId, gridNum, kindId) {
        var showData = pieData.showData;//饼图显示数据
        for(var t=0;t<showData.length;t++){
            showData[t].name=showData[t].name.replace('电信局','');
        }
        console.log(showData);
        toolBoxData=pieData;
        //饼图
        require.config({paths: {echarts: '<%=path%>/ywgl/js/echarts/build/dist'}});
        require(
            ['echarts', 'echarts/chart/pie'],
            function (ec) {
                var myChart2 = ec.init(document.getElementById('chart2'));
                var bill_regions = pieData.showCategory;//['东区', '南区', '西区', '北区', '中区', '浦东', '莘闵', '宝山', '嘉定', '松江', '青浦', '奉贤', '金山', '崇明'];
                bill_regions=getShowCategories(bill_regions);
                var center_total = pieData.centerPies;//[];//[{value:38695, name:'各区局工单总数'}];
                //ajax--end
                var option =
                    {
                        legend: {
                            orient: 'vertical',
                            x: 'left',
                            data: bill_regions
                        },
                       /* title: {
                            text: '',
                            subtext: '工单达标统计'
                        },*/
                        tooltip: {
                            trigger: 'item',
                            //formatter: //"{a} <br/>{b} : {c} ({d}%)"
                            formatter: function (params) {
                                var pie_pos = 0;
                                var showCats=option.legend.data;
                                for (var i = 0; i < showCats.length; i++) {
                                    if (showCats[i] == params.data.name) {
                                        pie_pos = i;
                                    }
                                }
                                if(params.series.name=='pieTotal'){
                                    //代表是中间内环,只返回总数和名称就好 pieTotal下面有定义
                                    return params.data.name + "<br>工单总数:"+ params.data.value;
                                }

                                var commonTip=params.data.name + "<br>工单总数:"+ params.data.value+"<br>工单执行数:"+toolBoxData.showData[pie_pos].executeNum+"<br>工单执行率: "+getShowDigitPercent(toolBoxData.showData[pie_pos].executeRate )+"<br>";
                                if(kindId==1){
                                    return commonTip+"非线路工单有效执行率:"+getShowDigitPercent(toolBoxData.showData[pie_pos].notXianluEffectiveExeRate );
                                }else if(kindId==3){
                                    return commonTip+"工程配合率:"+getShowDigitPercent(toolBoxData.showData[pie_pos].cooperateEfficiency );
                                }else if(kindId==2){
                                    return params.data.name + "<br>5*8NOC直派现场故障处理总数:"
                                        +toolBoxData.showData[pie_pos].nocNum+
                                        "<br>现场响应数"+toolBoxData.showData[pie_pos].zaclResponseNum+
                                        "<br>现场认领数"+toolBoxData.showData[pie_pos].zaclAcceptNum
                                        +"<br>现场响应率:"+
                                        getShowDigitPercent(toolBoxData.showData[pie_pos].zaclResponseRate )
                                        +"<br>现场认领率:"+getShowDigitPercent(toolBoxData.showData[pie_pos].zaclAcceptRate );
                                }
                            }
                        },
                        toolbox: {
                            show: true,
                            feature: {
                                mark: {show: false},
                                dataView: {show: false, readOnly: false},
                                magicType: {
                                    show: false,
                                    type: ['pie', 'funnel']
                                },
                                restore: {show: false},
                                saveAsImage: {show: true}
                            }
                        },

                        calculable: false,
                        series: [
                            {
                                name: 'pieTotal',
                                type: 'pie',
                                selectedMode: 'single',
                                radius: [0, 70],
                                x: '20%',
                                width: '40%',
                                funnelAlign: 'right',
                                max: 1548,

                                itemStyle: {
                                    normal: {
                                        label: {
                                            position: 'inner'
                                        },
                                        labelLine: {
                                            show: false
                                        }
                                    }
                                },
                                data: center_total//var center_total=[{value:38695, name:'总数'}];
                            },
                            {
                                name: '区局',
                                type: 'pie',
                                radius: [100, 140],

                                // for funnel
                                x: '60%',
                                width: '35%',
                                funnelAlign: 'left',
                                max: 1048,
                                data: showData
                            }
                        ]
                    };
                myChart2.setOption(option);
                var ecConfig = require('echarts/config');
                myChart2.on(ecConfig.EVENT.PIE_SELECTED, function (param) {
                    var selected = param.selected;
                    var serie;
                    for (var idx in selected) {
                        serie = option.series[idx];
                        for (var i = 0, l = serie.data.length; i < l; i++) {
                            if (selected[idx][i]) {
                                if (idx == "1" && pieLayer == 1) {
                                    //alert( serie.name + ' : ' + '【数据' + i + '】' + serie.data[i].name + ' ');
                                    regionId = showData[i].showId;
                                    //step1:根据当前区局Id钻取第二层网格数据
                                    var pieData2 = getPieData(2, userPoint, billYear, billMonth, regionId, gridNum, kindId);
                                    pieHrefPieData=pieData2;
                                    pieLayer = 2;//代表是第二层
                                    toolBoxData=pieData2;
                                    var showData2 = pieData2.showData;
                                    var center_total2 = pieData2.centerPies;
                                    var billGrids = pieData2.showCategory;
                                    //step2:覆盖旧数据
                                    var option2 =option;
                                    option2.legend.data=billGrids;
                                    option2.series[1].data=showData2;
                                    option2.series[0].data=center_total2;
                                    //step3:清空旧数据并填充新数据
                                    myChart2.clear();
                                    myChart2.setOption(option2);
                                    $("#returnBtn").show();
                                    //getEchartsPie(pieData2,userPoint, billYear, billMonth, regionId, gridNum, kindId);///这种方式会出现饼图容器还没生成 数据却先出来的错误(Cannot read property 'isLoading' of null)
                                } else if (idx == "1" && pieLayer == 2) {
                                    var myShowData=pieHrefPieData.showData;
                                    if (myShowData == null || myShowData == undefined || myShowData == "" || myShowData.length == 0) {
                                        myShowData=globalPieData.showData;//这里判断是因为如果一开始直接跳到第二层网格的,那么数据直接拿一开始加载到的饼图数据
                                    }
                                   // console.log(myShowData);
                                    var j_pos=-1;
                                    for(var j=0;j<myShowData.length;j++){
                                        if(myShowData[j].name==serie.data[i].name){
                                            j_pos=j;break;
                                        }
                                    }
                                    if(j_pos==-1) {alert('无法跳转到详单数据,请联系技术支持!');return;}
                                    var orgId=myShowData[j].orgId;
                                    if(kindId==2){//网故的详单表比较特殊
                                        window.open("<%=echartsFineReportUrl%>?reportlet=billFailDetailZacl.cpt&accessToken=<%=accessToken%>&kindId=" + kindId+"&billYear="+billYear+"&billMonth="+billMonth+"&orgId="+orgId+"&isZwAccept=yes&isClaim=yes", window, "height=600, width=1400, center=Yes, status=no,resizable=yes");
                                    }else{
                                        var cpt='';//具体跳到哪张报表设置
                                        if(kindId==1){//作业计划
                                            cpt='billFailDetailZyjh.cpt&isExecute=yes&isNotXianlu=yes';
                                        }else{//工程配合
                                            cpt='billFailDetailGcph.cpt&isExecute=yes';
                                        }
                                        window.open("<%=echartsFineReportUrl%>?reportlet="+cpt+"&accessToken=<%=accessToken%>&kindId=" + kindId+"&billYear="+billYear+"&billMonth="+billMonth+"&orgId="+orgId+"&tableName="+getBillInfoTablePostfix(billYear,billMonth), window, "height=600, width=1400, center=Yes, status=no,resizable=yes");
                                    }
                                  }
                            }
                        }
                    }
                });
            });
    }
    

效果图:


图3.1.1 饼图效果图
图3.1.2 点击某一个区显示该区下的分布数据

3.2 柱形图

功能描述:柱形图加载各分类数据,同时可点击柱子跳到其他页面。

function getEchartsGcclBar(billYear, billMonth, regionId, gridNum, kindId, showType) {
        //故障处理柱形图
        require.config({
            paths: {
                echarts: '<%=path%>/ywgl/js/echarts/build/dist'
            }
        });
        require(['echarts', 'echarts/chart/line', 'echarts/chart/bar'],
            function (ec) {
                var zyjh_legend = ['5*8NOC直派现场故障处理总数', '现场响应数', '现场认领数', '现场响应率', '现场认领率'];
                var myChart = ec.init(document.getElementById('chart'));
                var gzcl_zs_data = [];//[2500, 3000, 2817, 3000, 2100, 1500, 2400];
                var bill_regions = [];//['东区', '南区', '西区', '北区', '中区', '浦东', '莘闵', '宝山', '嘉定', '松江', '青浦', '奉贤', '金山', '崇明'];
                var gzcl_response = [];//[41,96,168,146,86,314,220,71,100,151,78,118,62,19];
                var gzcl_accept = [];//[42,100,173,145,89,316,221,70,100,154,79,118,62,18];
                var gzcl_accept_rate = [];//[0.9545,0.9901,0.9886,0.9864,1.0,1.0,0.9910,0.9859,0.9901,0.9809,1.0,0.9593,0.8378,0.9474];
                var gzcl_response_rate = [];//[0.9318,0.9505,0.96,0.9932,0.9332,0.9937,0.9865,1.0,0.9901,0.9618,0.9873,0.9593,0.8378,1.0];
                //提示
                var noc_num = [];//[44,101,175,147,89,316,223,71,101,157,79,123,74,19];
                var donghuan_num = [];//[12,4,21,12,15,29,28,7,7,14,14,17,13,14];
                var xianlu_num = [];//[0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                var region_number = [];//[32,21,44,53,6,96,53,49,56,77,58,81,41,3];
                var wuxian_num = [];//[0,76,110,82,68,191,142,15,38,66,7,25,20,2];
                var showId=[];
                $.ajax({
                    async: false,
                    dataType: "json",
                    type: "post",
                    url: '<%=path%>/unionbill/getEchartsBar.do',
                    data: {
                        "showType": showType,
                        "userId": "<%=userId%>",
                        "userPoint": userPoint,
                        "billYear": billYear,
                        "billMonth": "" + billMonth,
                        "regionId": regionId,
                        "gridNum": gridNum,
                        "kindId": kindId
                    },
                    success: (function (data) {
                        //showid..........
                        gzcl_zs_data = data.nocNum;
                        bill_regions = data.showCategory;
                        bill_regions=getShowCategories(bill_regions);
                        gzcl_response = data.zaclResponseNum;
                        gzcl_accept = data.zaclAcceptNum;
                        gzcl_accept_rate = data.zaclAcceptRate;
                        gzcl_response_rate = data.zaclResponseRate;
                        //提示
                        noc_num = data.nocNum;
                        donghuan_num = data.moveRingZaclNum;
                        xianlu_num = data.xianluZaclNum;
                        region_number = data.juneiZaclNum;//局内
                        wuxian_num = data.wuxianZaclNum;
                        showId=data.showId;
                    })
                });//ajax--end
                var option = {
                    title: {
                        text: '',
                        subtext: '工单完成情况统计[工单场景:故障处理]'
                    },
                    tooltip: {
                        trigger: 'axis',
                        formatter: function (params) {
                            var b_pos = 0;
                            for (var i = 0; i < bill_regions.length; i++) {
                                if (bill_regions[i] == params[0].name) {
                                    b_pos = i;
                                }
                            }
                            return params[0].name + ':<br>5*8NOC直派现场故障处理总数: ' + noc_num[b_pos] + ' <br>现场响应数: ' + gzcl_response[b_pos] + ' <br> 现场认领数: ' + gzcl_accept[b_pos] +
                                '<hr>现场响应率: ' + getShowDigitPercent(gzcl_response_rate[b_pos] )+ ' <br>现场认领率: ' + getShowDigitPercent(gzcl_accept_rate[b_pos] ) +
                                '<hr>动环故障数: ' + donghuan_num[b_pos] + '<br>局内故障数: ' + region_number[b_pos] + '<br>无线故障数: ' + wuxian_num[b_pos] + '<br>线路故障数: ' + xianlu_num[b_pos];
                        }
                    },
                    legend: {
                        data: zyjh_legend
                    }
                    ,
                    toolbox: {
                        show: true,
                        feature: {
                            mark: {show: false},
                            dataView: {show: false, readOnly: false},
                            magicType: {show: false, type: ['line', 'bar']},
                            restore: {show: false},
                            saveAsImage: {show: true}
                        }
                    },
                    calculable: true,
                    grid: {y: 60, y2: 30, x2: 50},
                    xAxis: [
                        {
                            type: 'category',
                            data: bill_regions
                        },
                        {
                            type: 'category',
                            axisLine: {show: false},
                            axisTick: {show: false},
                            axisLabel: {show: false},
                            splitArea: {show: false},
                            splitLine: {show: false},
                            data: bill_regions
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            axisLabel: {formatter: '{value} '}
                        },
                        {
                            type: 'value',
                            name: '现场响应率',
                            axisLabel: {
                                formatter: '{value}        '
                            }
                        },
                        {
                            type: 'value',
                            name: '现场认领率',
                            axisLabel: {
                                formatter: '{value}        '
                            }
                        }
                    ],
                    series: [
                        {
                            name: '5*8NOC直派现场故障处理总数',
                            type: 'bar',
                            xAxisIndex: 1,
                            itemStyle: {
                                normal: {
                                    color: '#aed268',//rgba(237,129,29,0.5)',
                                    label: {
                                        show: true
                                    }
                                }
                            },
                            data: gzcl_zs_data
                        },
                        {
                            name: '现场响应数',
                            type: 'bar',
                            xAxisIndex: 0,
                            itemStyle: {
                                normal: {
                                    color: '#c475ad',//rgba(181,195,52,1)',
                                    label: {
                                        show: true
                                    }
                                }
                            },
                            data: gzcl_response
                        },
                        {
                            name: '现场认领数',
                            type: 'bar',
                            xAxisIndex: 0,
                            itemStyle: {
                                normal: {
                                    color: '#48aae0',//'rgba(193,35,43,1)',
                                    label: {
                                        show: true
                                    }
                                }
                            },
                            data: gzcl_accept
                        }

                        , {
                            name: '现场认领率',
                            type: 'line',
                            yAxisIndex: 1,
                            data: gzcl_accept_rate
                        }, {
                            name: '现场响应率',
                            type: 'line',
                            yAxisIndex: 1,
                            data: gzcl_response_rate
                        }
                    ]
                };
                myChart.setOption(option);
                var ecConfig = require('echarts/config');
                myChart.on(ecConfig.EVENT.CLICK, function (param) {
                    var bar_zacl_pos = 0;
                    for (var i = 0; i < bill_regions.length; i++) {
                        if (bill_regions[i] == param.name) {
                            bar_zacl_pos = i;
                      }
                    }
                    var regionHref=showId[bar_zacl_pos];
                    var monthHref=billMonth;//默认按区局的跳转参数
                    if(billMonth.length>1){//多月即x轴是按月
                        //按月份的跳转参数
                        // 此时跳转带过去的regionid应该是页面下拉框的值
                        //月份就是柱子的Id
                        regionHref=regionId;
                        monthHref=showId[bar_zacl_pos];
                    }

                    if(param.seriesIndex!=0){//5*8Noc总数柱子不需要跳转
                        var diff='';
                        if(param.seriesIndex==1){//现场响应数
                            diff='&isZwAccept=yes';
                        }else{
                            //现场认领数
                            diff='&isClaim=yes';
                        }
                        window.open("<%=echartsFineReportUrl%>?reportlet=billFailDetailZacl.cpt&kindId=" + kindId+diff+"&accessToken=<%=accessToken%>&billYear="+billYear+"&billMonth="+monthHref+"&regionId="+regionHref, window, "height=600, width=1400, center=Yes, status=no,resizable=yes");
                    }
                    //window.open("http://localhost:8075/WebReport/ReportServer?reportlet=billFailDetail.cpt&kindId=" + kindId+"&billYear="+billYear+"&billMonth="+monthHref+"&regionId="+regionHref, window, "height=600, width=1400, center=Yes, status=no,resizable=yes");
                });
            });// 路径配置  //画echarts柱形图
    }//故障处理柱形图end

功能效果图


图3.2.1 柱形图效果图

3.3 环图

function drawPie(){
         var mychart1 = echarts.init(document.getElementById('mychart1'));
         var mychart2=echarts.init(document.getElementById('mychart2'));
        var mychart3=echarts.init(document.getElementById('mychart3'));
        var mychart4=echarts.init(document.getElementById('mychart4'));
        var mychart5=echarts.init(document.getElementById('mychart5'));
         var option = {
             series: [{type: 'pie',radius: ['50%', '70%'],
                     label: {
                         normal: {
                             show: false,
                             position: 'center'
                         }
                     },
                     data: [
                         {value: 0.9, name: ''},
                         {value: 0.1, name: ''}
                     ],
                     color: ['#87CEEB', '#DCDCDC'],
                     animation: false
                 }
             ]
         };
         //获取数据
        $.ajax({
            async: false,
            dataType: "json",
            type: "post",
            url: '<%=echartsAppUrl%>',
            data: {
                "accessToken": "<%=accessToken%>",
                "type": "getWelcomePieData"
            },
            success: (function (data) {
               console.log(data);
               //作业计划的数据
                option=setValueIntoOption(option,data,1,1);
                mychart1.setOption(option);
                option=setValueIntoOption(option,data,1,2);
                mychart2.setOption(option);
                //故障处理--响应率
                option=setValueIntoOption(option,data,2,1);
                mychart3.setOption(option);
                //故障处理--认领率
                option=setValueIntoOption(option,data,2,2);
                mychart4.setOption(option);
                //工程配合--工程配合率
                option=setValueIntoOption(option,data,3,1);
                mychart5.setOption(option);
            })
        });//ajax--end
        //

    }
function setValueIntoOption(option,data,kind,idx) {
    if(kind==1){
        if(data.detail.zyjhEchartsBar!=null){
            if(idx==1){
                option.series[0].data[0].value=data.detail.zyjhEchartsBar.executeRate;
                option.series[0].data[1].value=1-data.detail.zyjhEchartsBar.executeRate;
                option.series[0].color=['#87CEEB', '#DCDCDC'];
                $("#zyjhOne").html(getShowDigitPercent(option.series[0].data[0].value));
            }else{
                option.series[0].data[0].value=data.detail.zyjhEchartsBar.notXianluExecuteRate;
                option.series[0].data[1].value=1-data.detail.zyjhEchartsBar.notXianluExecuteRate;
                option.series[0].color=['#00CD66', '#DCDCDC'];
                $("#zyjhTwo").html(getShowDigitPercent(option.series[0].data[0].value));
            }
        }else{
            option.series[0].data[0].value=0;
            option.series[0].data[1].value=1;
            option.series[0].color=['#f35c30', '#DCDCDC'];
            $("#zyjhOne").html(getShowDigitPercent(option.series[0].data[0].value));
            $("#zyjhTwo").html(getShowDigitPercent(option.series[0].data[0].value));
        }
    }else if(kind==2){
        if(data.detail.zaclEchartsBar!=null) {
            //故障处理
            if (idx == 1) {
                option.series[0].data[0].value = data.detail.zaclEchartsBar.zaclResponseRate;
                option.series[0].data[1].value = 1 - data.detail.zaclEchartsBar.zaclResponseRate;
                option.series[0].color = ['#f35c30', '#DCDCDC'];
                $("#zaclOne").html(getShowDigitPercent(option.series[0].data[0].value));
            } else {
                option.series[0].data[0].value = data.detail.zaclEchartsBar.zaclAcceptRate;
                option.series[0].data[1].value = 1 - data.detail.zaclEchartsBar.zaclAcceptRate;
                option.series[0].color = ['#f3c930', '#DCDCDC'];
                $("#zaclTwo").html(getShowDigitPercent(option.series[0].data[0].value));
            }
        }else{
            option.series[0].data[0].value=0;
            option.series[0].data[1].value=1;
            option.series[0].color=['#f35c30', '#DCDCDC'];
            $("#zaclOne").html(getShowDigitPercent(option.series[0].data[0].value));
            $("#zaclTwo").html(getShowDigitPercent(option.series[0].data[0].value));
        }
    }else if(kind==3){
        if(data.detail.gcphEchartsBar!=null) {
            //工程配合
            if (idx == 1) {
                option.series[0].color = ['#7B68EE', '#DCDCDC'];
                option.series[0].data[0].value = data.detail.gcphEchartsBar.cooperateEfficiency;
                option.series[0].data[1].value = 1 - data.detail.gcphEchartsBar.cooperateEfficiency;
                $("#gcphOne").html(getShowDigitPercent(option.series[0].data[0].value));
            }
        }else{
            option.series[0].data[0].value=0;
            option.series[0].data[1].value=1;
            option.series[0].color=['#f35c30', '#DCDCDC'];
            $("#gcphOne").html(getShowDigitPercent(option.series[0].data[0].value));
        }
    }
    return option;
}

显示百分比如果带小数位保留两位小数,否则直接取整

function getShowDigitPercent(showDigit) {
    if(showDigit*100!=(showDigit*100).toFixed(2)){
        //说明有小数此时保留二位小数
        return (showDigit*100).toFixed(2)+"%"
    }else{
        return showDigit*100+"%";
    }
}

显示效果图如下 :


图3.3.1 环图
上一篇下一篇

猜你喜欢

热点阅读