现在位置首页 / 项目实战 /正文

echart图表控件配置入门(二)常用图表数据动态绑定

作者: IT小兵 | 2015年5月7日| 热度:℃ | 评论: |参与:

上一节 《echart图表控件配置入门(一)》介绍了echarts图表控件的入门配置,使开发人员可以快速搭建出一个静态的图表。但是在实际开发过程这还是不够的,不可能所有的图表控件都是静态数据。决大部份图表是需要读取后台大量的数据时行可视化展示。图表较区表格形式的数据在可视化方面是有一定的优势。能使用户可以快速看出数据存在的问题、趋势、比较分析。因为人类对图表中的颜色、大小、形状更加敏感。

现在分别对折线图、柱状图、饼图、中国地图四类图表的数据绑定进行详细的介绍。echarts中其它的图表方法都差不多,只要了解官方的demo,按照指定的数据结构进行解析都能很方便的得到想要的结果;

echarts中提供了setOption、setSeries两个方法可以对图表的相关数据和属性进行动态设置,setOption一定要在setSeries之前设置;

var myChart = ec.init(document.getElementById('div1'));
var ecConfig = require('echarts/config');                
var option = {
    title: {
        text: '标题',
        x:"center"
    },
    tooltip: {
        trigger: 'axis'
    },
    legend: {
        data:[],
        y:"bottom"
    },
    toolbox: {
        show: true,
        feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true }
        }
    },
    xAxis: [{
        type: 'category',
        data:[] 
    }],
    yAxis: [{
        type: 'value'
    }],
    series: []
};

option中的属性可以通过对象属性的方式获取设置;例如以上代码中,

option.legend.data=["xx","xx"] 可以通过这种方法设置对应属性的值

option.title.text="改变标题";//改变标题属性

option.xAxis[0]["data"]=[];//改变坐标值


myChart.setOption(option);//设置图表对象的所有参数属性

myChart.setSeries(seriesData);//设置图表对象的数据集合

通过后台交互数据肯定会有一定的延迟,这时最好能有一个友好载入提示,echarts提供showLoading方法

// 载入动画提示
myChart.showLoading({
    text: '正在努力的读取数据中...'
});
//取消载入提示
myChart.hideLoading();

来几个具体的实例吧。

以下实例的ajax用jquery的$.ajax。所以如果你要在本地测试,需要引用jquery.js。 

这里所有demo虽然也请求了后台。但都是通过前后模拟了一个返回的json数据。不管各位是搞jsp、asp、php的都没关系,只要按指定的格式生成对的格式的json数据就行了。

至于后台如何生成json数据,各自就baidu下吧。这里就不提了。

 

通过官方的demo我可以看到哪些属性是需要动态传入数据,然后我们按照格式传入对应的值或数组;


通过demo的代码。我们可以看出折线标红的地方需要动态设置分别是

option.title.text="标题";

option.legend.data=["图例1","图例2","……"];

option.xAxis[0]["data"]=["一","二","三","……"];//x轴数据

var seriesData=[

  {

    name:"图例1",

    type:"line",

    data:[1,2,3]

  }

]

myChart.setOption(option);  //设置全部参数属性
myChart.setSeries(seriesData);//设置图例数据

通过以上方法就可以实现动态的echarts数据改变了。

1、折线图

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>数据绑定 柱状图</title>   
    <script src="../js/jquery-1.7.min.js" type="text/javascript"></script>
    <script src="../build/source/echarts.js" type="text/javascript"></script>
</head>
<body>
<div id="div1" style="width:900px;height:400px;border:1px solid #dddddd;margin:10px auto;"></div>
<script type="text/javascript">
        require.config({
            paths: {
                echarts: '../build/dist' //引用资源文件夹路径,注意路径
            }
        });
        require(
            [
                'echarts',
                'echarts/chart/bar',
                'echarts/chart/line'
            ],
            function (ec) {
                var myChart = ec.init(document.getElementById('div1'));
                var ecConfig = require('echarts/config');                
                var option = {
                    title: {
                        text: '',
                        x:"center"
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data:[],
                        y:"bottom"
                    },
                    toolbox: {
                        show: true,
                        feature: {
                            mark: { show: true },
                            dataView: { show: true, readOnly: false },
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: { show: true }
                        }
                    },
                    xAxis: [{
                        type: 'category',
                        data:[] 
                    }],
                    yAxis: [{
                        type: 'value'
                    }],
                    series: []
                };
                // 载入动画---------------------
                myChart.showLoading({
                    text: '正在努力的读取数据中...',    //loading话术
                });
                $.ajax({
                    url:"Default.aspx",
                    data:{},
                    success:function(data){
                        //数据接口成功返回
                        //后台需要返回以下结构的json数据
                        data={
                            "legen":["访问量","订单数"],
                            "axis":['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                            "series":[
                                [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
                                [4.0, 2.9, 6.0, 21.2, 50.6, 56.7, 115.6, 102.2, 62.6, 20.0, 9.4, 3.3]
                            ]
                        };
                        var legendData=[];
                        var xAxisData=[];
                        var seriesData=[];
                        if(data!=null && data["series"].length>0){
                            legendData=data["legen"];
                            xAxisData=data["axis"];
                            for(var i=0,len=data["series"].length;i<len;i++){
                                seriesData.push({
                                    "name":legendData[i],
                                    "type":"line",
                                    "data":data["series"][i]
                                });
                            }
                        }
                        option.title.text="折线图标题";
                        option.legend.data=legendData;
                        option.xAxis[0]["data"]=xAxisData;
                        myChart.setOption(option);
                        myChart.setSeries(seriesData);
                    },
                    error:function(){
                        //数据接口异常处理
                        var legendData=[''];
                        var xAxisData=[''];
                        var seriesData = [
                                {
                                    name:'',
                                    type: 'line',
                                    data: [0]
                                }
                        ];                    
                        option.legend.data=legendData;
                        option.xAxis[0]["data"]=xAxisData;
                        myChart.setOption(option);
                        myChart.setSeries(seriesData);
                    
                    },
                    complete:function(){      
                        //不管数据接口成功或异常,都终于载入提示              
                        //停止动画载入提示                    
                        myChart.hideLoading(); 
                    }
                });
            }
        ); 
    
    </script>
</body>
</html>

2、柱状图 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>数据绑定 柱状图</title>   
    <script src="../js/jquery-1.7.min.js" type="text/javascript"></script>
    <script src="../build/source/echarts.js" type="text/javascript"></script>
</head>
<body>
<div id="div1" style="width:900px;height:400px;border:1px solid #dddddd;margin:10px auto;"></div>
<script type="text/javascript">
        require.config({
            paths: {
                echarts: '../build/dist' //引用资源文件夹路径,注意路径
            }
        });
        require(
            [
                'echarts',
                'echarts/chart/bar',
                'echarts/chart/line'
            ],
            function (ec) {
                var myChart = ec.init(document.getElementById('div1'));
                var ecConfig = require('echarts/config');                
                var option = {
                    title: {
                        text: '标题',
                        x:"center"
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data:[],
                        y:"bottom"
                    },
                    toolbox: {
                        show: true,
                        feature: {
                            mark: { show: true },
                            dataView: { show: true, readOnly: false },
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: { show: true }
                        }
                    },
                    xAxis: [{
                        type: 'category',
                        data:[] //['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
                    }],
                    yAxis: [{
                        type: 'value'
                    }],
                    series: []
                };
                // 载入动画---------------------
                myChart.showLoading({
                    text: '正在努力的读取数据中...',    //loading话术
                });
                $.ajax({
                    url:"Default.aspx",
                    data:{},
                    success:function(data){
                        //后台需要返回以下结构的json数据
                        data={
                            "legen":["访问量","订单数"],
                            "axis":['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                            "series":[
                                [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
                                [4.0, 2.9, 6.0, 21.2, 50.6, 56.7, 115.6, 102.2, 62.6, 20.0, 9.4, 3.3]
                            ]
                        }
                        var legendData=[];
                        var xAxisData=[];
                        var seriesData=[];
                        if(data!=null && data["series"].length>0){
                            legendData=data["legen"];
                            xAxisData=data["axis"];
                            for(var i=0,len=data["series"].length;i<len;i++){
                                seriesData.push({
                                    "name":legendData[i],
                                    "type":"bar",   //柱状图和拆线图类似只要将bar 改成line
                                    "data":data["series"][i]
                                });
                            }
                        }
                        option.legend.data=legendData;
                        option.xAxis[0]["data"]=xAxisData;
                        myChart.setOption(option);
                        myChart.setSeries(seriesData);
                    },
                    error:function(){
                        var legendData=[''];
                        var xAxisData=[''];
                        var seriesData = [
                                {
                                    name:'订单数',
                                    type: 'bar',    //柱状图和拆线图类似只要将bar 改成line
                                    data: [0]
                                }
                        ];                    
                        option.legend.data=legendData;
                        option.xAxis[0]["data"]=xAxisData;
                        myChart.setOption(option);
                        myChart.setSeries(seriesData);
                    
                    },
                    complete:function(){                    
                        //停止动画载入提示                    
                        myChart.hideLoading(); 
                    }
                });
            }
        ); 
    
    </script>
</body>
</html>

3、饼图 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>数据绑定 饼图</title>   
    <script src="../js/jquery-1.7.min.js" type="text/javascript"></script>
    <script src="../build/source/echarts.js" type="text/javascript"></script>
</head>
<body>
<div id="div1" style="width:900px;height:400px;border:1px solid #dddddd;margin:10px auto;"></div>
<script type="text/javascript">
        require.config({
            paths: {
                echarts: '../build/dist' //引用资源文件夹路径,注意路径
            }
        });
        require(
            [
                'echarts',
                'echarts/chart/bar',
                'echarts/chart/line',
                'echarts/chart/pie'
            ],
            function (ec) {
                var myChart = ec.init(document.getElementById('div1'));
                var ecConfig = require('echarts/config');                
                var option = {
                    title: {
                        text: '标题',
                        x:"center"
                    },
                    tooltip: {
                        trigger: 'item',                        
                        formatter: "{a} <br/>{b} : {c} ({d}%)"
                    },
                    legend: {
                        data:[],
                        y:"bottom"
                    },
                    calculable : true,
                    toolbox: {
                        show: true,
                        feature: {
                            mark: { show: true },
                            dataView: { show: true, readOnly: false },
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: { show: true }
                        }
                    },
                    series: []
                };
                // 载入动画---------------------
                myChart.showLoading({
                    text: '正在努力的读取数据中...',    //loading话术
                });
                $.ajax({
                    url:"Default.aspx",
                    data:{},
                    success:function(data){
                        //后台需要返回以下结构的json数据
                        data={
                            "legen":["访问量","订单数","购买数"],
                            "series":[4440,3220,1110]
                        }
                        var legendData=[];
                        var seriesData=[];
                        if(data!=null && data["series"].length>0){
                            legendData=data["legen"];
                            seriesData.push({
                                "name":"饼图标例1",
                                "type":"pie",
                                "radius" : '55%',   //饼图半径大小
                                "center": ['50%', '60%'],//饼图圆心位置x,y
                                "data":function(){
                                    var t_data=[];
                                    for(var i=0,len=data["series"].length;i<len;i++){
                                        t_data.push({
                                            "name":legendData[i],
                                            "value":data["series"][i]                                        
                                        });
                                    }
                                    return t_data;                                    
                                }()
                            });
                        }
                        option.legend.data=legendData;
                        myChart.setOption(option);
                        myChart.setSeries(seriesData);
                    },
                    error:function(){
                        var legendData=[''];
                        var seriesData = [
                                {
                                "name":"饼图标例1",
                                "type":"pie",
                                "radius" : '55%',   //饼图半径大小
                                "center": ['50%', '60%'],//饼图圆心位置x,y
                                    data: [0]
                                }
                        ];                    
                        option.legend.data=legendData;                        
                        myChart.setOption(option);
                        myChart.setSeries(seriesData);
                    
                    },
                    complete:function(){                    
                        //停止动画载入提示                    
                        myChart.hideLoading(); 
                    }
                });
            }
        ); 
    
    </script>
</body>
</html>

4、中国地图

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>数据绑定 中国地图</title>   
    <script src="../js/jquery-1.7.min.js" type="text/javascript"></script>
    <script src="../build/source/echarts.js" type="text/javascript"></script>
</head>
<body>
<div id="div1" style="width:900px;height:400px;border:1px solid #dddddd;margin:10px auto;"></div>
<script type="text/javascript">
        require.config({
            paths: {
                echarts: '../build/dist' //引用资源文件夹路径,注意路径
            }
        });
        require(
            [
                'echarts',
                'echarts/chart/bar',
                'echarts/chart/line',
                'echarts/chart/map'
            ],
            function (ec) {
                var myChart = ec.init(document.getElementById('div1'));
                var ecConfig = require('echarts/config');    
                
                var mapType = [
                    'china',
                    '广东', '青海', '四川', '海南', '陕西',
                    '甘肃', '云南', '湖南', '湖北', '黑龙江',
                    '贵州', '山东', '江西', '河南', '河北',
                    '山西', '安徽', '福建', '浙江', '江苏',
                    '吉林', '辽宁', '台湾',
                    '新疆', '广西', '宁夏', '内蒙古', '西藏',
                    '北京', '天津', '上海', '重庆',
                    '香港', '澳门'
                ];            
                var option = {
                    title: {
                        text: '标题',
                        x:"center"
                    },
                    tooltip: {
                        trigger: 'item',                        
                        formatter: "{a} <br/>{b} : {c} ({d}%)"
                    },
                    legend: {
                        data:[],
                        y:"bottom"
                    },
                    dataRange: {
                        min: 0,
                        max:50000,  //最好通过对数据计算得出,不要写死
                        x: 'left',
                        y: 'bottom',
                        text:['高','低'],           // 文本,默认为数值文本
                        calculable : true
                    },
                    toolbox: {
                        show: true,
                        feature: {
                            mark: { show: true },
                            dataView: { show: true, readOnly: false },
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: { show: true }
                        }
                    },
                    series: []
                };
                // 载入动画---------------------
                myChart.showLoading({
                    text: '正在努力的读取数据中...',    //loading话术
                });
                $.ajax({
                    url:"Default.aspx",
                    data:{},
                    success:function(data){
                        //后台需要返回以下结构的json数据
                        data={
                            "legen":["访问量","订单数"],
                            "series":[
                                [{"name":"上海","value":31417.76},{"name":"云南","value":5828.25},{"name":"其他","value":0.00},{"name":"内蒙古","value":297.00},{"name":"北京","value":25683.00},{"name":"吉林","value":3044.38},{"name":"四川","value":26890.66},{"name":"天津","value":11341.98},{"name":"宁夏","value":297.00},{"name":"安徽","value":1553.00},{"name":"山东","value":17969.81},{"name":"山西","value":2675.20},{"name":"广东","value":51438.63},{"name":"广西","value":4806.00},{"name":"新疆","value":5788.21},{"name":"江苏","value":76003.09},{"name":"江西","value":12879.03},{"name":"河北","value":7811.25},{"name":"河南","value":3772.00},{"name":"浙江","value":13383.12},{"name":"海南","value":0.00},{"name":"湖北","value":22250.17},{"name":"湖南","value":12925.44},{"name":"甘肃","value":7561.56},{"name":"福建","value":22143.76},{"name":"西藏","value":1802.40},{"name":"贵州","value":6961.41},{"name":"辽宁","value":8506.00},{"name":"重庆","value":14562.92},{"name":"陕西","value":3939.03},{"name":"青海","value":0.00},{"name":"黑龙江","value":2010.28}],
                                [{"name":"上海","value":31417.76},{"name":"云南","value":5828.25},{"name":"其他","value":0.00},{"name":"内蒙古","value":297.00},{"name":"北京","value":25683.00},{"name":"吉林","value":3044.38},{"name":"四川","value":26890.66},{"name":"天津","value":11341.98},{"name":"宁夏","value":297.00},{"name":"安徽","value":1553.00},{"name":"山东","value":17969.81},{"name":"山西","value":2675.20},{"name":"广东","value":51438.63},{"name":"广西","value":4806.00},{"name":"新疆","value":5788.21},{"name":"江苏","value":76003.09},{"name":"江西","value":12879.03},{"name":"河北","value":7811.25},{"name":"河南","value":3772.00},{"name":"浙江","value":13383.12},{"name":"海南","value":0.00},{"name":"湖北","value":22250.17},{"name":"湖南","value":12925.44},{"name":"甘肃","value":7561.56},{"name":"福建","value":22143.76},{"name":"西藏","value":1802.40},{"name":"贵州","value":6961.41},{"name":"辽宁","value":8506.00},{"name":"重庆","value":14562.92},{"name":"陕西","value":3939.03},{"name":"青海","value":0.00},{"name":"黑龙江","value":2010.28}]
                             ]
                        }
                        var legendData=[];
                        var seriesData=[];
                        if(data!=null && data["series"].length>0){
                            legendData=data["legen"];                  
                            for(var i=0,len=data["series"].length;i<len;i++){
                                seriesData.push({
                                    "name":legendData[i],
                                    "type":"map",
                                    "mapType":"china",
                                    "roam":false,
                                    "itemStyle":{
                                        "normal":{"label":{show:true}},
                                        "emphasis":{"label":{show:true}}
                                    },
                                    "data": data["series"][i]                                    
                                });
                            }
                        }
                        option.legend.data=legendData;
                        myChart.setOption(option);
                        myChart.setSeries(seriesData);
                    },
                    error:function(){
//                        var legendData=[''];
//                        var seriesData = [
//                                {
//                                "name":"饼图标例1",
//                                "type":"pie",
//                                "radius" : '55%',   //饼图半径大小
//                                "center": ['50%', '60%'],//饼图圆心位置x,y
//                                    data: [0]
//                                }
//                        ];                    
//                        option.legend.data=legendData;                        
//                        myChart.setOption(option);
//                        myChart.setSeries(seriesData);
                    
                    },
                    complete:function(){                    
                        //停止动画载入提示                    
                        myChart.hideLoading(); 
                    }
                });
            }
        ); 
    
    </script>
</body>
</html>

注意dataRange的max和min会影响到颜色深度的。因为当前值会和最大值求比,然后计算颜色深度。

可以通过dataRange的color:['#dddddd','#777777'] 设置max,min的颜色值


参考:

http://www.cnblogs.com/web369/p/4365166.html


[asp.net+echarts2.0线状态柱状图联动实例及demo]

[echarts教程:制表折线图柱状图饼图等的入门介绍]

[echarts2.0的部署和使用完整步骤]

[echarts教程--echarts单击和双击实现的模拟实现]

点击阅读本文所属分类的更多文章: 项目实战 。和高手一起交流:346717337
友荐云推荐

未注明转发、原文均为本站原创。分享本文请注明 原文链接

给您更多信息和帮助

在这里您可以找到更多:

技术交流群:346717337 Jquery插件交流

投稿:suchso@vip.qq.com

承接:企业网站门户/微网站/微商城/CMS系统/微信公众号运营/业务咨询

抢天猫双11红包
推荐使用阿里云服务器
echarts教程系列
本月最热文章

微信扫一扫,徜徉悠嘻网,您的休闲乐园

微信公众号:快乐每一天

随机文章
标签

技术交流群:346717337

投稿:suchso@vip.qq.com

专业专注:企业网站门户/微网站/微商城/CMS系统/微信公众号运营/付费问题咨询