echarts系列之動態加載數據


1.echarts學習前言

最近接觸到echarts,發現數據可視化真的是魅力無窮啊,各種變幻的曲線交錯,以及‘曼妙’的動畫效果真是讓人如痴如醉!

下面就來一起欣賞她的美...

“ ECharts是中國的,也是世界的。”

      —— 浙江大學教授 · 陳為

“ ECharts,發現數據可視化之美!”

     ——中國傳媒大學教授 · 沈浩

大數據時代
              重新定義數據圖表的時候到了......

2.echarts的demo代碼

需求:ajax請求到json格式數據,動態添加到曲線和表格中

jquery:1.8.3版本

bootstrap:2.3.2版本

用代碼說話是我們的游戲規則(吼吼):

echarts/qiyue.html 中 qiyue.html文件:

<html>
    <head>
        <title>*echarts*</title>
        <meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
        <script src="js/jquery-1.8.3.min.js"></script>
        <script src="js/bootstrap.min.js"></script>
        <script src="js/echarts.js"></script>
        <style type="text/css">
            *{
                font-family: "微軟雅黑";
            }
            .count-title{
                padding-bottom: 15px;
                margin-bottom: 20px;
                border-bottom: 1px solid #ccc;
            }
            #main{
                width: 100%;
                height: 500px;
                margin: 0 auto;
            }
            .total-incre{
                padding-left: 147px;
                margin-top: 5px;
                position: absolute;
            
            }
            .total-incre strong{
                color: #e5903a;
            }
            .chooseTime{
                position: absolute;
                right: 100px;
                top:18px;
            }
            .table td,.table th{
                text-align: center;
            }
            .agencyNew{
                width: 90%;
            }
        </style>
        
    </head>
    <body>
        <div class="container agencyNew">
            <div class="row">
                <!-- Split button -->

                <h1 class="count-title">XX銷售情況</h1>
                
                <p class="total-incre">
                    合計:<strong class="total">888</strong> | 新增 :<strong class="increase">88</strong>
                </p>
                <!--下拉框-->                
                <div class="dropdown chooseTime">
                  <a class="btn btn-default dropdown-toggle" role="button" data-toggle="dropdown" data-target="#" >
                        最近一個月
                    <b class="caret"></b>
                  </a>
                  <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
                        <li><a href="#">最近一個月</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#">2017年2月</a></li>
                        <li><a href="#">2017年1月</a></li>
                  </ul>
                </div>
                <!--echarts曲線容器-->
                <div id="main">
                    
                </div>
                <!--表格-->
                <table class="table table-bordered table-striped table-hover">
                    <thead>
                        <!--動態獲取表頭-->
                        
                    </thead>
                    <tbody>
                        <!--動態獲取表格-->
                    </tbody>
                </table>
            </div>
        </div>
    </body>
    <script src="http://echarts.baidu.com/build/dist/echarts.js"></script>
    <script src="js/qiyue.js"></script>
    
</html>

echarts/js/qiyue.js 中 qiyue.js文件:

var myChart,option;
$(function(){    
        require.config({
            paths: {
                'echarts': 'http://echarts.baidu.com/build/dist'
            }
        });
        
        require(
            [
                'echarts',
                'echarts/chart/line',   // 按需加載所需圖表,如需動態類型切換功能,別忘了同時加載相應圖表
                'echarts/chart/bar'
            ],
            function (ec) {
                myChart = ec.init(document.getElementById('main'));
                option  = {
                   title: {
                        text: 'XX銷售情況',
                        subtext: ''
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: []
                    },
                    toolbox: {
                         show : true,
                        feature : {
                            mark : {show: true},
                            dataView : {show: true, readOnly: false},
                            magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                            restore : {show: true},
                            saveAsImage : {show: true}
                        }
                    },
                    
                    xAxis: [
                         {
                                type : 'category',
                                boundaryGap : false,
                                data : [ ]
                                ,
                                axisLabel: {
                                    interval:0,//橫軸信息全部顯示
                                    rotate: 30,//60度角傾斜顯示
                                    formatter:function(val){
//                                        return val.split("").join("\n"); //橫軸信息文字豎直顯示
                                        return val;
                                    },
                                    textStyle: {
                                        color: '#000',
                                        align: 'center',
                                        fontWeight: 'bold'
                                    }
                                
                                }
                           }
                    ],
                    yAxis: [],
                    series: []
                };
//                myChart = require('echarts').init(document.getElementById('main'));
                myChart.showLoading({
//                    text : '數據獲取中',
                    effect: 'whirling'
                });
                getData();
                

                
           });
});
        
//請求json
var fields,
     itemsMap,
     seriesItem,
    yAxis_arr = [],
    thead     = '',
     tbody     = '',
    tbody_tr  = '';
        function getData(){
            $.ajax({
                url      : 'data0.json',
                dataType : 'json', 
                async    : false,
                type     : 'get',
                success  : function(json){
//                    console.log(json.data);
                    console.log(option);
                    fields   = json.data.fields;
                    itemsMap = json.data.itemsMap;
                    
                    createEcharts();//動態創建曲線圖
                    createTab();//動態創建表格
                    myChart.hideLoading();
                    myChart.setOption(option);
                    
                },
               
                error : function(XMLHttpRequest, textStatus, errorThrown){
                     
                    if(textStatus == 'parsererror'){
                        
                        alert('數據為空或者SQL語句錯誤!');
                    }
                    
                    console.log(errorThrown);
                }
            });
        }

/*
 * 動態創建曲線圖
 */
function createEcharts(){
                    
    //    series                
    for(var i=1; i<fields.length; i++){
        if(i==1){
            itemStyle = {
                    normal: {
                        areaStyle: {
                            type: 'default'
                        }
                    }
            };
        }else{
            itemStyle = {
                    normal: {
                        color: '#70bf41'
                       
                    }
            };
        }
        option.legend.data.push(fields[i]);  //    legend
        seriesItem              = {};
        seriesItem.name      = fields[i];
        seriesItem.type      = 'line';
        seriesItem.smooth    = false;
        seriesItem.yAxisIndex= i-1;
        seriesItem.itemStyle = itemStyle;

        seriesItem.data      = [];
        
        for(var key in itemsMap){
            seriesItem.data.push(itemsMap[key][i]);
        }

//        填充默認顯示曲線的數據
        option.series.push(seriesItem);
//        option.series[0].type      = 'line';
//        option.series[1].type      = 'bar';
        // yAxis    
        var yAxis_obj  = {};
        yAxis_obj.type = 'value';
        yAxis_obj.name = fields[i];
        yAxis_obj.show = true;
        yAxis_arr.push(yAxis_obj);
        
    }
        option.yAxis = yAxis_arr;
        console.log(yAxis_arr);
        
}
/*
 * 動態創建表格
 */
function createTab(){
    //動態創建表頭
    for(var i=0; i<fields.length; i++){
        
        thead += '<th>'+fields[i]+'</th>';
        $('.table thead').html('<tr>'+thead+'</tr>');

    }
    
    for(var j in itemsMap){
        var tbody_td = '';
        option.xAxis[0].data.push(itemsMap[j][0]); // XAxis
        for(var k=0; k<itemsMap[j].length; k++){
            
              tbody_td += '<td>'+itemsMap[j][k]+'</td>';
            
        }
//        console.log(tbody_td);
        tbody_tr += '<tr>'+tbody_td+'</tr>';
    }    
    $('.table tbody').html(tbody_tr);
        
}

echarts/data0.json 中data0.json文件:

{
    "data": {
        "itemsMap": {
            "1": ["2017-03-1", "3", "8"],
            "2": ["2017-03-2", "18", "20"],
            "3": ["2017-03-3", "43", "54"],
            "4": ["2017-03-4", "50", "74"],
            "5": ["2017-03-5", "39", "41"],
            "6": ["2017-03-6", "20", "52"],
            "7": ["2017-03-7", "21", "25"],
            "8": ["2017-03-8", "16", "26"],
            "9": ["2017-03-9", "10", "11"],
            "10": ["2017-03-10", "8", "10"]
            
        },                        
        "fields": ["日期", "預購", "成交"],
        "status": 1
    }
}

3.運行結果展示

由於鵝的博客還沒有直接運行功能,為了瀏覽方便我就把效果圖貼上吧(= =)

tips:所有數據純屬虛構哦。

源代碼在github上提供https://github.com/yingliyu/commonDemo.git


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM