Baidu Data Visualization Chart Suite Echart Combat

Source: Internet
Author: User



Recently I have been working on the front end of data visualization, the most drawing tool I have used is D3. D3 a bit like Photoshop, the function is very powerful, the example is also many, but the study cost is not low, does the project to need the big manpower investment. At the end of March by the students working in the Amazon introduced the use of Echart, a Baidu front-end launched by the Canvas Domestic library (official website: http://echarts.baidu.com/index.html). This echart is actually in the Canvas class library zrender based on the theme of the library, the advantages of data-driven, legend rich, powerful, support data drag and drop recalculation, data area roaming, all Chinese documents very enjoyable. With the same domestic front-end scaffolding FIS like (official website http://fis.baidu.com/), are sincere full of domestic packages, embodies the current domestic good front-end development strength. Use them feel like you want to make a tablet computer, go to Huaqiang North a turn, motherboard, CPU, screen and so on a variety of packages an order, things on the rushing to assemble up. Extremely efficient and ideal for commercial project development. And even for research, using these can be a good basis.



Echart Chart Library Hierarchy relationship


1. Introduction of Catalogs


Needless to say, see good things, the first step is to get all the relevant files down from GitHub, and then go to the build directory to gathered up things. The new directory is as follows:



echarts-1.3.8
--zrender//zrender is Echart rely on the drawing library, the official website requires download, but at present my program does not directly refer to it, it can be said that under normal circumstances Echart can run independently
--–zrender.js
--EXCANVAS_R3//excanvas is a tool to implement ie7,8 compatible canvas drawing, realizes most of the canvas API, in the drawing aspect its core is through the IE's VML to realize, the efficiency is low
--–excanvas.js
--echarts.js//echarts Main program, contains all the theme gallery except map. Note that this is compressed and can only be loaded via Requirejs or Esl.js modules, and if you want to load with a label or sea.js, use the Echarts-plain.js
--echarts-orginal.js//Non-compressed echarts.js
--echarts-map.js//echarts's Map theme Gallery





2. Implement the demo in your project


This echart is Baidu front-end do, they recommend the use of modular development. Fortunately, my previous project was developed using Requirejs + ANGULARJS. So it's easier to introduce.



First, add Echart to the Requirejs Portal configuration file Main.js:


require.config ({

     baseUrl: ‘application / views / frontEnd / build /’
     , paths: {
         // Omit some configuration information here ...
         // echart and its components
         , echarts: ‘lib / echarts-1.3.8 / echarts’
         , "echarts / chart / line": ‘lib / echarts-1.3.8 / echarts’
         , "echarts / chart / bar": ‘lib / echarts-1.3.8 / echarts’
         , ‘Echarts / chart / scatter’: ‘lib / echarts-1.3.8 / echarts’
         , ‘Echarts / chart / k’: ‘lib / echarts-1.3.8 / echarts’
         , ‘Echarts / chart / pie’: ‘lib / echarts-1.3.8 / echarts’
         , ‘Echarts / chart / radar’: ‘lib / echarts-1.3.8 / echarts’
         , ‘Echarts / chart / map’: ‘lib / echarts-1.3.8 / echarts’
         , ‘Echarts / chart / chord’: ‘lib / echarts-1.3.8 / echarts’
         , ‘Echarts / chart / force’: ‘lib / echarts-1.3.8 / echarts’
         , zrender: ‘lib / echarts-1.3.8 / zrender / zrender’
     }
     , priority: [
         ‘Angular’
     ]
     //,urlArgs:‘v=1.1 ’
});





Then, in the specific page to introduce Echart control JS file, load dependent.


define ([
         ‘Echarts’,
         ‘Echarts / chart / pie’,
         ‘D3’
     ], function (ec) {

         function common_chart_staff_assess_ctrl ($ http, $ scope) {
         // controller for angularjs ...
         }
     }
     return common_chart_staff_assess_ctrl;
});





The above two steps, familiar with dojo or Requirejs friends should be no pressure, but still have a lot of friends do not use these, so it is necessary to say a bit.



Then it is the official website of the example on their own page to achieve. Here I choose a special thousand layer pie chart, click here to see the original image on the official website.



Then we take the static data (option object) in the example to our own JS file, and then follow the example of the official website to write a rendering & Refresh function


// Rendering & refresh function
            $ scope.refresh = function (option, isBtnRefresh) {
                if (isBtnRefresh) {
                    needRefresh = true;
                    if (needRefresh) {
                        myChart.showLoading ();
                        setTimeout ($ scope.refresh (option), 500);
                    }
                    return;
                }
                needRefresh = false;
                if (myChart && myChart.dispose) {
                    myChart.dispose ();
                }
                myChart = ec.init (domMain);
                window.onresize = myChart.resize;
                myChart.setOption (option, true);
                domMessage.innerHTML = ‘‘;
            };

//Test Data
$ scope.option = {
    title: {
        text: ‘browser ratio change’,
        subtext: ‘Pure fiction’,
        x: ‘right’,
        y: ‘bottom’
    },
    tooltip: {
        trigger: ‘item’,
        formatter: "{a} <br} {b}: {c} ({d}%)"
    },
    legend: {
        orient: ‘vertical’,
        x: ‘left’,
        data: [‘Chrome’, ‘Firefox’, ‘Safari’, ‘IE9 +’, ‘IE8-’]
    },
    toolbox: {
        show: true,
        feature: {
            mark: {show: true},
            dataView: {show: true, readOnly: false},
            restore: {show: true},
            saveAsImage: {show: true}
        }
    },
    calculable: false,
    series: (function () {
        var series = [];
        for (var i = 0; i <30; i ++) {
            series.push ({
                name: ‘Browser (data is purely fictitious)’,
                type: ‘pie’,
                itemStyle: {normal: {
                    label: {show: i> 28},
                    labelLine: {show: i> 28, length: 20}
                }},
                radius: [i * 4 + 40, i * 4 + 43],
                data: [
                    {value: i * 128 + 80, name: ‘Chrome’},
                    {value: i * 64 + 160, name: ‘Firefox’},
                    {value: i * 32 + 320, name: ‘Safari’},
                    {value: i * 16 + 640, name: ‘IE9 +‘},
                    {value: i * 8 + 1280, name: ‘IE8-’}
                ]
            })
        }
        series [0] .markPoint = {
            symbol: ‘emptyCircle’,
            symbolSize: series [0] .radius [0],
            effect: {show: true, scaleSize: 12, color: ‘rgba (250,225,50,0.8)’, shadowBlur: 10, period: 30},
            data: [{x: ‘50% ’, y: ‘50%‘}]
        };
        return series;
    }) ()
};
setTimeout (function () {
    var _ZR = myChart.getZrender ();
    // replenish the millennial cake
    _ZR.addShape ({
        shape: ‘text’,
        style: {
            x: _ZR.getWidth () / 2,
            y: _ZR.getHeight () / 2,
            color: ‘# 666’,
            text: `` The Past of Nightmares '',
            textAlign: ‘center’
        }
    });
    _ZR.addShape ({
        shape: ‘text’,
        style: {
            x: _ZR.getWidth () / 2 + 200,
            y: _ZR.getHeight () / 2,
            brushType: ‘fill’,
            color: ‘orange’,
            text: ‘Better Future’,
            textAlign: ‘left’,
            textFont: ‘normal 20px Microsoft Yahei’
        }
    });
    _ZR.refresh ();
}, 2000);





Then find a div on the page to show Echart.



However, please note that you must set the width of the div height, otherwise the figure does not show that I do not blame.


<section class="span12">     
    <div id="graph" class="graph chart-area" style="height:500px"></div>
</section>




I used bootstrap here, the width is changed by the percentage value of the grid system, so the above code does not specify a width. Finally debug debugging, no problem I can also show here. 3. Customization


Of course, it is not satisfying for me to just stay in the case of quoting others.



First, you want to do data binding.



This is subdivided into 3 steps:


  1. Analyzing the data format (that is, analyzing the option object, this step requires careful separation of the data and style information obtained in the background. So I set the $scope.option object to store the default style configuration information in the code, then Ajax gets the data and then extend the two. )
  2. Assemble the corresponding data in the background (depending on the needs, I only take numerical information, not many words)
  3. Front desk Ajax gets real data (this is pretty good, but my code uses the Angularjs encapsulated $.post object to do this)
  4. // Set the real data format
    $ scope.default_option = {
        title: {
            text: ‘Fault Type Time Series Annual Ring Diagram’,
            subtext: ‘This chart shows the percentage of the frequency of various types of faults from the inside to the outside, and their laws that change with time’,
            x: ‘right’,
            y: ‘bottom’
        },
        tooltip: {
            trigger: ‘item’,
            formatter: "{a} <br} {b}: {c} ({d}%)"
        },
        legend: {
            orient: ‘vertical’,
            x: ‘left’,
            selected: $ scope.faultnameSelected
            , data: $ scope.faultname
        },
        toolbox: {
            show: true,
            feature: {
                mark: true,
                dataView: {readOnly: false},
                restore: true,
                saveAsImage: true
            }
        },
        calculable: false,
        series: {}
    };
    
     $ scope.ajaxChartData = function (dataname) {
        myChart.showLoading ({
            text: `` Reading data ... '', // loading
        });
        $ http.post ("index.php / main / readfaultnum", null) .success (function (alldata) {
            console.log (alldata);
            var option = $ scope.default_option;
            option.series = $ scope.setData (alldata);
            $ scope.refresh (option, true);
            $ scope.order = dataname;
    
            myChart.hideLoading ();
    
        }). error (function () {
            domMessage.innerHTML = ‘Network failure, failed to get data’;
        });
     };
    











5. Further customization



Although I used the official website example to achieve the needs, but I also have some of my own ideas.



On the website of the Thousand Layer pie chart, the representative time of the ring width is fixed. But the data that we read from the background (measured in months) is variable in time and grows with the increase in system usage time. This leads to a problem, that is, in only one months, only a small ring, 50 months, the ring more than the display range. This is not beautiful, and has lost a certain degree of usability.



I decided to optimize it. The rings will be wide when few data are used in the month, and the rings will be very thin when many data are used in the month, so it is possible to avoid losing usability when the data volume is small and the data is large. Of course, if the amount of data is too large, the rings will be too thin, the same loss of availability. So we're going to set a threshold for the maximum amount of data and cut out the excess.



The solution is to scale the ring width based on the amount of data, that is, using the scale function. In Echart I have not found such a scale function for the time being. Of course, the linear scale is simple, and functions can be written by themselves. But other types of scale scaling are a little tricky. Fortunately, I have been using the D3 class library to do the visualization, I know that D3 has such a scale function can easily solve my problem. That is the D3.scale object, which contains linear scale, square scale, exponential scale, set scale, can fully meet the needs. I can extract the scale function from the open source D3 library and introduce it to this page. Based on the test results of the actual data, I chose the square scale. Well, then it's good to write:


 

var maxTime = 36; // This pie chart displays data for up to 60 months (up to 60 circles)
// Processing factory function of raw data
$ scope.setData = function (data) {
    // This is the square scale function of D3, used to scale the width of the ring based on the size of the data
    var rScale = d3.scale.sqrt ()
            .domain ([maxTime, 1])
            .range ([3, 30])
            .nice ();
    console.log (rScale (1), rScale (12), rScale (36))
    // If the amount of data exceeds 60 (that is, there are 60 months), delete the data before 60 months and only display the content of the last 60 months
    if (data.length> maxTime) {
        data.splice (0, maxTime);
    }
    // The width of the ring calculated by D3 scale
    var R = rScale (data.length);
    console.log (R);
    for (var i = 0; i <data.length; i ++) {
        data [i] [‘type‘] = ‘pie’;
        data [i] [‘radius’] = [i * R + 40, i * R + 40 + R];
        //if(typeof($scope.times[i])!= null)
        data [i] [‘name’] = $ scope.times [i];
        data [i] [‘itemStyle’] = {normal: {
            label: {show: i> (data.length-2)},
            labelLine: {
                show: i> (data.length-2),
                length: 40,
                color: ‘# f0f’,
                width: 10,
                type: ‘dotted’
            }
        }};
    }

    // Display the central text
    setTimeout (function () {
        var myDate = new Date ();
        var myMouth = myDate.getMonth () + 1;
        var myYear = myDate.getFullYear (); // Get the full year (4 digits, 1970-????)

        // Supplement the explanatory text in the center of Melaleuca
        var _ZR = myChart.getZrender ();
        _ZR.addShape ({
            shape: ‘text’,
            style: {
                x: _ZR.getWidth () / 2,
                y: _ZR.getHeight () / 2,
                color: ‘orange’,
                text: data.length + ‘month ago’,
                textAlign: ‘center’
            }
        });
        _ZR.addShape ({
            shape: ‘text’,
            style: {
                x: _ZR.getWidth () / 2 + data.length * R +50,
                y: _ZR.getHeight () / 2,
                color: ‘orange’,
                strokeColor: ‘pink’,
                text: ‘today’ + myYear + "year" + myMouth + "month",
                textAlign: ‘left’,
                textFont: ‘normal 14px Microsoft Yahei’
            }
        });
        _ZR.refresh ();
    }, 500);

    return data;
};
In this way, the tree-ring graphs are available regardless of the size of the data:


Only 4 months of data in the ring chart



30-month test data for the ring chart






Of course, to do this step, although the realization of the demand, but after all, according to other people's example of modification, not the depth of their own creation. However, how to create their own, more than the scope of this article, and not this blog can be included in the future to discuss.



5. Browser Compatibility:



Finally, a browser compatibility issue must be mentioned. IE8, IE7 Browser is not compatible with canvas drawing (IE6 allow me to ignore directly), in order to achieve compatibility need to introduce EXCANVAS_R3 library.


12345 <! --Le HTML5 Shim, forIE6-8 support ofHTML5elements- - > <! --[ifltIE9]> <script src="Application/views/frontend/build/lib/html5shiv.js"></script > <script src="Application/views/frontend/build/lib/echarts-1.3.8/excanvas/excanvas.js" ></script> <! [endif]-->


Sometimes IE8 in the drawing dislocation, add the following code to enable IE7 compatibility mode can be resolved:


1234 <! --Solving canvas drawing dislocation in IE8- -> <! --[iflt IE9]> <Meta http-equiv="x-ua-compatible"content="Ie=7" /> <! [endif]-->





Baidu Data Visualization Chart Suite Echart Combat


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.