Spring MVC與EChart繪製圖表(二)

在上一文章中,我們簡單介紹了柱狀圖的繪製方法,今天主要介紹一下餅狀圖和折線圖的繪製方法。採用的封裝類還是上一篇文章的,此處不再累述。話不多說,直接上代碼。

1、餅狀圖

前端:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>ECharts餅狀圖</title>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/echarts-all.js"></script>
</head>
<body>
<!--定義頁面圖表容器-->
<!-- 必須制定容器的大小(height、width) -->
<div id="main"
     style="height: 400px; border: 1px solid #ccc; padding: 10px;"></div>

<script type="text/javascript">
    $().ready(function () {
        var myChart = echarts.init(document.getElementById('main'));
        //圖表顯示提示信息
        myChart.showLoading();
        //定義圖表options
        var options = {
            title: {
                x: 'center', // 'center' | 'left' | {number},
                y: 'top', // 'center' | 'bottom' | {number}
                text: '信息發送方式'
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            legend: {
                orient: 'horizontal', // 'vertical'
                // 分組的位置設置,可以爲座標
                x: 'center', // 'center' | 'left' | {number},
                y: 'bottom', // 'center' | 'bottom' | {number}
                data: []
            },
            series: [{
                name: '發送方式',
                type: 'pie',
                data: [],
                // 餅狀圖數值和比例顯示
                itemStyle: {
                    normal: {
                        label: {
                            show: true,
                            formatter: '{b} : {c} ({d}%)'
                        },
                        labelLine: {show: true}
                    }
                }
            }]
        };
        //通過Ajax獲取數據
        $.ajax({
            type: "post",
            async: false, //同步執行
            url: "showEChartPie.action",
            dataType: "json", //返回數據形式爲json
            success: function (result) {
                if (result) {
                    options.legend.data = result.legend;
                    //將返回的category和series對象賦值給options對象內的category和series
                    //因爲xAxis是一個數組 這裏需要是xAxis[i]的形式
                    options.series[0].name = result.series[0].name;
                    options.series[0].type = result.series[0].type;
                    var seriesData = result.series[0].data;
                    //jquery遍歷
                    var value = [];
                    $.each(seriesData, function (i, p) {
                        value[i] = {
                            'name': p['name'],
                            'value': p['value']
                        };
                    });
                    options.series[0]['data'] = value;
                    myChart.hideLoading();
                    myChart.setOption(options);
                }
            },
            error: function (errorMsg) {
                alert("圖表請求數據失敗啦!");
            }
        });

    });
</script>

</body>
</html>

其中,以下代碼適用於控制餅狀圖上的數值和比例的顯示:

itemStyle: {
    normal: {
       label: {
           show: true,
            // 顯示格式
           formatter: '{b} : {c} ({d}%)'
              },
        labelLine: {show: true}
            }
}

後臺代碼:

    public EChartData PieData() {
        List<Statistic> statisticList = service.selectListGroupBySource();
        List<String> legend = new ArrayList<String>();
        List<Map> seriesData=new ArrayList<Map>();
        for (Statistic statistic:statisticList){
            Map map = new HashMap();
            legend.add(statistic.getSource());
            // 科目,對應餅狀圖每一部分的名稱
            map.put("name",statistic.getSource());
            // 數值
            map.put("value",statistic.getTotal());
            seriesData.add(map);
        }
        List<Series> series = new ArrayList<Series>();// 縱座標
        // Series參數:1、介紹;2、類型;3、數值集合
        series.add(new Series("發送方式", "pie",seriesData));
        return new EChartData(legend,null, series,null);
    }

效果圖:

2、折線圖

前端:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/echarts-all.js"></script>
</head>
<title>ECharts折線圖</title>
<body>
<!--定義頁面圖表容器-->
<!-- 必須制定容器的大小(height、width) -->
<div id="main"
     style="height: 400px; border: 1px solid #ccc; padding: 10px;"></div>

<script type="text/javascript">
    $().ready(
        function() {
            var myChart = echarts.init(document.getElementById('main'));
            //圖表顯示提示信息
            myChart.showLoading();
            //定義圖表options
            var options = {
                color: {
                    data: []
                },
                title: {
                    x: 'center', // 'center' | 'left' | {number},
                    y: 'top', // 'center' | 'bottom' | {number}
                    text: "通過Ajax獲取數據呈現圖標示例"
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    orient: 'horizontal', // 'vertical'
                    x: 'center', // 'center' | 'left' | {number},
                    y: 'bottom', // 'center' | 'bottom' | {number}
                    data: []
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: false
                    }
                },
                calculable: true,
                xAxis: [
                    {
                        type: 'category',
                        data: []
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        splitArea: { show: true }
                    }
                ],
                series: []
            };

            //通過Ajax獲取數據
            $.ajax({
                type : "post",
                async : false, //同步執行
                url : "showEChartLine.action",
                dataType : "json", //返回數據形式爲json
                success : function(result) {
                    if (result) {
                        //將返回的category和series對象賦值給options對象內的category和series
                        //因爲xAxis是一個數組 這裏需要是xAxis[i]的形式
                        options.xAxis[0].data = result.category;
                        options.series = result.series;
                        options.legend.data = result.legend;
                        options.color = result.color;
                        myChart.hideLoading();
                        myChart.setOption(options);
                    }
                },
                error : function(errorMsg) {
                    alert("圖表請求數據失敗啦!");
                }
            });

        });
</script>
</body>
</html>

當數據較密集時,可以控制橫座標數值不顯示,避免數據過大,橫座標顯示不美觀,具體方法是修改xAxis的屬性:

                xAxis: [
                    {
                        type: 'category',
                        // 默認爲true
                        show: false,
                        data: []
                    }
                ],

後臺:

public EChartData lineData() {
        List<Visit> visitList = visitService.queryAll();
        List<String> category = new ArrayList<String>();
        List<Long> visitData=new ArrayList<Long>();
        List<Long> registerData=new ArrayList<Long>();
        for (Visit visit:visitList){
            category.add(visit.getDate());
            visitData.add(visit.getVisit());
            registerData.add(visit.getRegister());
        }
        List<String> legend = new ArrayList<String>(Arrays.asList(new String[] { "visit","register" }));// 數據分組
        List<Series> series = new ArrayList<Series>();// 縱座標
        // 折線1
        series.add(new Series("visit", "line", visitData));
        // 折線2
        series.add(new Series("register", "line", registerData));
        return new EChartData(legend, category, series, Arrays.asList(ChartUtil.getColorList(legend.size())));
    }

效果圖:

很多時候,可能需要同時繪製多個圖表,但又不想機械性地重複代碼,關於這種場景,我們下一篇文章進行介紹同時繪製多個圖表的實現與封裝。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章