HighCharts使用心得

HighCharts使用心得

前言:

以前很早的一個項目中使用過highcharts,感受挺方便的,圖表類型也比較豐富,並且還支持數據的下鑽,可是若是投入商業使用的話還會有一些版權的問題,因此後來就使用了EChart,這是百度開發的一個開源的圖表插件,圖表類型也很豐富,並且還有交互,對地圖的支持也很好,能夠免費的使用。在以前的一篇文章裏,已經總結過了,今天主要跟你們分享一下,以前總結的Highcharts的一些使用心得,但願可以對你們有所幫助。javascript

1.  準備工做------下載HighCharts插件

跟ECharts同樣,HighCharts也須要下載相應的插件,不過HightCharts的插件很簡單,只有一個highcharts.js文件。能夠從HighCharts官網上下載,具體地址以下:http://www.highcharts.com/downloadjava

另注:jquery

若是須要導出圖表,則須要exporting.js文件數組

若是須要一些特殊的圖形呈現,則還須要下載highcharts-more.js網站

2.  新建一個解決方案或網站,引用下載的highcharts.js文件,進行圖表展現。

在這個過程當中,我會逐步的跟你們講解如何使用highcharts.js進行圖表展現。this

2.1 新建解決方案(或網站),目錄結構以下

 

另注:spa

通常狀況下若是不須要導出圖片、且只使用常規的圖形,exportting.js和highchart-more.js能夠不要,只留一個highcharts.js文件便可。prototype

其中的HighCharts.js文件爲我本身總結的使用幫助文件,主要用來配置圖表類型、圖表數據的處理、格式化等操做,下邊會進一步講解。插件

             此外須要注意的是這裏引用的Jquery文件版本爲最近版本,VS裏邊默認的爲1.4.1的版本過低,最新的highcharts須要高版本的jQuery文件。3d

2.2 HighChart.js文件介紹

在2.1中對此文件有一個初步的介紹,這一小節裏專門來介紹這個文件。該文件的主要功能是用來配置各類圖表類型的配置項,同時對用戶提供的參數進行格式化、圖表的呈現等功能。

文件的目錄結構以下:

var HighChart = {

    ChartDataFormate: {//數據格式化

        FormateNOGroupData: function (data) {//處理不分組的數據

            var categories = [];

            var datas = [];

            for (var i = 0; i < data.length; i++) {

                categories.push(data[i].name || "");

                datas.push([data[i].name, data[i].value || 0]);

            }

            return { category: categories, data: datas };

        },…………

       },

    ChartOptionTemplates: {//圖表配置項

        Pie: function (data, name, title) {

            var pie_datas = HighChart.ChartDataFormate.FormateNOGroupData(data);

            var option = {

                chart: {

                    plotBackgroundColor: null,

                    plotBorderWidth: null,

                    plotShadow: false

                },

               …….

            };

            return option;

        },

    RenderChart: function (option, container) {//頁面渲染

        container.highcharts(option);

    }

  

完整代碼:

//document.write("<script language='javascript' src='/Scripts/jquery-1.11.0.min.js'></script>");//引入Jquery(1.8.0以上版本)
//document.write("<script language='javascript' src='/Statics/highcharts.js'></script>"); //引入hightcharts引擎
//document.write("<script language='javascript' src='/Statics/exporting.js'></script>"); //引入導出圖片js

//判斷數組中是否包含某個元素
Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

var HighChart = {
    ChartDataFormate: {
        FormateNOGroupData: function (data) {
            var categories = [];
            var datas = [];
            for (var i = 0; i < data.length; i++) {
                categories.push(data[i].name || "");
                datas.push([data[i].name, data[i].value || 0]);
            }
            return { category: categories, data: datas };
        },
        FormatGroupData: function (data) {//處理分組數據,數據格式:name:XXX,group:XXX,value:XXX用於折線圖、柱形圖(分組,堆積)
            var names = new Array();
            var groups = new Array();
            var series = new Array();
            for (var i = 0; i < data.length; i++) {
                if (!names.contains(data[i].name))
                    names.push(data[i].name);
                if (!groups.contains(data[i].group))
                    groups.push(data[i].group);
            }
            for (var i = 0; i < groups.length; i++) {
                var temp_series = {};
                var temp_data = new Array();
                for (var j = 0; j < data.length; j++) {
                    for (var k = 0; k < names.length; k++)
                        if (groups[i] == data[j].group && data[j].name == names[k])
                            temp_data.push(data[j].value);
                }
                temp_series = { name: groups[i], data: temp_data };
                series.push(temp_series);
            }
            return { category: names, series: series };
        },
        FormatBarLineData: function (data, name, name1) {//數據類型:name:XXX,value:XXX,處理結果主要用來展現X軸爲日期的具備增幅的趨勢的圖
            var category = [];
            var series = [];
            var s1 = [];
            var s2 = [];
            for (var i = 1; i < data.length; i++) {
                if (!category.contains(data[i].name))
                    category.push(data[i].name);
                s1.push(data[i].value);
                var growth = 0;
                if (data[i].value != data[i - 1].value)
                    if (data[i - 1].value != 0)
                        growth = Math.round((data[i].value / data[i - 1].value - 1) * 100);
                    else
                        growth = 100;
                s2.push(growth);
            }
            series.push({ name: name, color: '#4572A7', type: 'column', yAxis: 1, data: s1, tooltip: { valueStuffix: ''} });
            series.push({ name: name1, color: '#89A54E', type: 'spline', yAxis: 1, data: s2, tooltip: { valueStuffix: '%'} });
            return { series: series };
        }
    },
    ChartOptionTemplates: {
        Pie: function (data, name, title) {
            var pie_datas = HighChart.ChartDataFormate.FormateNOGroupData(data);
            var option = {
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false
                },
                title: {
                    text: title || ''
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true
                    }
                },
                series: [{
                    type: 'pie',
                    name: name || '',
                    data: pie_datas.data
                }]
            };
            return option;
        },
        DrillDownPie: function (data, name, title) {
            var drilldownpie_datas;
            var option = {
                chart: {
                    type: 'pie'
                },
                title: {
                    text: title || ''
                },
                subtitle: {
                    text: '請點擊餅圖項看詳細佔比'
                },
                plotOptions: {
                    series: {
                        dataLabels: {
                            enabled: true,
                            format: '{point.name}: {point.y:.1f}%'
                        }
                    }
                },
                tooltip: {
                    headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
                    pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
                },
                series: [{
                    name: name || '',
                    colorByPoint: true,
                    data: drilldownpie_datas.fir_data
                }],
                drilldown: {
                    series: drilldownpie_datas.series
                }
            };
            return option;
        },
        Line: function (data, name, title) {
            var line_datas = HighChart.ChartDataFormate.FormatGroupData(data);
            var option = {
                title: {
                    text: title || '',
                    x: -20
                },
                subtitle: {
                    text: '',
                    x: -20
                },
                xAxis: {
                    categories: line_datas.category
                },
                yAxis: {
                    title: {
                        text: name || ''
                    },
                    plotLines: [{
                        value: 0,
                        width: 1,
                        color: '#808080'
                    }]
                },
                tooltip: {
                    valueSuffix: ''
                },
                legend: {
                    layout: 'horizontal',
                    align: 'center',
                    verticalAlign: 'bottom'
                },
                series: line_datas.series
            };
            return option;
        },
        Bars: function (data, is_stack, is_stack_percent, name, title) {
            var bars_datas = HighChart.ChartDataFormate.FormatGroupData(data);
            var option = {
                chart: {
                    type: 'column'
                },
                title: {
                    text: title || ''
                },
                subtitle: {
                    text: ''
                },
                credits: {
                    enabled: false
                },
                xAxis: {
                    categories: bars_datas.category
                },
                yAxis: {
                    //min: 0,
                    title: {
                        text: name
                    }
                },
                tooltip: {
                    headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                    pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name};</td>' +
                        '<td style="padding:0"><b>{point.y:.1f}</b></td></tr>',
                    footerFormat: '</table>',
                    shared: true,
                    useHTML: true
                },
                plotOptions: {
                    column: {
                        pointPadding: 0.2,
                        borderWidth: 0
                    }
                },
                series: bars_datas.series
            };
            var stack_option = {};
            if (is_stack && !is_stack_percent) {
                stack_option = {
                    tooltip: {
                        formatter: function () {
                            return '<b>' + this.x + '</b><br/>' +
                        this.series.name + ': ' + this.y + '<br/>' +
                        'Total: ' + this.point.stackTotal;
                        }
                    },
                    plotOptions: {
                        column: {
                            stacking: 'normal',
                            dataLabels: {
                                enabled: true,
                                color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
                            }
                        }
                    }
                };
            }
            if (!is_stack && is_stack_percent) {
                stack_option = {
                    tooltip: {
                        pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',
                        shared: true
                    },
                    plotOptions: {
                        column: {
                            stacking: 'percent'
                        }
                    }
                };
            }
            return $.extend({}, option, stack_option);
        },
        Pyramid: function (data, name, title) {
            var pyramid_datas = HighChart.ChartDataFormate.FormateNOGroupData(data);
            var option = {
                chart: {
                    type: 'pyramid',
                    marginRight: 100
                },
                title: {
                    text: title || '',
                    x: -50
                },
                plotOptions: {
                    series: {
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b> ({point.y:,.0f})',
                            color: 'black',
                            softConnector: true
                        }
                    }
                },
                legend: {
                    enabled: false
                },
                series: [{
                    name: name || '',
                    data: pyramid_datas.data
                }]
            };
            return option;
        },
        BarLine: function (data, name, name1, title) {
            var barline_datas = HighChart.ChartDataFormate.FormatBarLineData(data);
            var option = {
                chart: {
                    zoomType: 'xy'
                },
                title: {
                    text: title || ''
                },
                subtitle: {
                    text: ''
                },
                xAxis: [{
                    categories: barline_datas.category
                }],
                yAxis: [{ // Primary yAxis
                    labels: {
                        format: '{value}',
                        style: {
                            color: '#89A54E'
                        }
                    },
                    title: {
                        text: name || '',
                        style: {
                            color: '#89A54E'
                        }
                    }
                }, { // Secondary yAxis
                    title: {
                        text: name1 || '',
                        style: {
                            color: '#4572A7'
                        }
                    },
                    labels: {
                        format: '{value}',
                        style: {
                            color: '#4572A7'
                        }
                    },
                    opposite: true
                }],
                tooltip: {
                    shared: true
                },
                legend: {
                    layout: 'horizontal',
                    align: 'center',
                    verticalAlign: 'bottom'
                },
                series: [{
                    name: 'Rainfall',
                    color: '#4572A7',
                    type: 'column',
                    yAxis: 1,
                    data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
                    tooltip: {
                        valueSuffix: ' mm'
                    }

                }, {
                    name: 'Temperature',
                    color: '#89A54E',
                    type: 'spline',
                    data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6],
                    tooltip: {
                        valueSuffix: '°C'
                    }
                }]




            };
        }
    },
    RenderChart: function (option, container) {
        container.highcharts(option);
    }
};

  

2.3 具體的頁面展現

2.3.1 餅圖

l  頁面引用

     <script src="../Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>

    <script src="../Statics/highcharts.js" type="text/javascript"></script>

    <script src="../Statics/exporting.js" type="text/javascript"></script>

    <script src="../Statics/HighChart.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(function () {

            var data = [{ name: 'olive', value: 116 }, { name: 'momo', value: 115 }, { name: 'only', value: 222 }, { name: 'for', value: 324}];

            var opt = HighChart.ChartOptionTemplates.Pie(data,'Love-Rate',"餅圖示例");

            var container = $("#container");

            HighChart.RenderChart(opt, container);

        });

    </script>

  

l  效果展現

 

2.3.2 折線圖

l  頁面引用

 

<script src="../Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>

    <script src="../Statics/highcharts.js" type="text/javascript"></script>

    <script src="../Statics/exporting.js" type="text/javascript"></script>

    <script src="../Statics/HighChart.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(function () {

            var data = [

            { name: '2013-01', group: 'olive', value: 116 },

            { name: '2013-01', group: 'momo', value: 115 },

            { name: '2013-01', group: 'only', value: 222 },

            { name: '2013-01', group: 'for', value: 324 },

            { name: '2013-02', group: 'olive', value: 156 },

            { name: '2013-02', group: 'momo', value: 185 },

            { name: '2013-02', group: 'only', value: 202 },

            { name: '2013-02', group: 'for', value: 34 },

            { name: '2013-03', group: 'olive', value: 16 },

            { name: '2013-03', group: 'momo', value: 51 },

            { name: '2013-03', group: 'only', value: 22 },

            { name: '2013-03', group: 'for', value: 84 }

            ];

            var opt = HighChart.ChartOptionTemplates.Line(data, 'Love-Rate', "折線圖示例");

            var container = $("#container");

            HighChart.RenderChart(opt, container);

        });

    </script>

 

  

l  效果展現

 

2.3.3 柱形圖

l  頁面引用

<script src="../Scripts/jquery-1.11.0.min.js" type="text/javascript"></script>

    <script src="../Statics/highcharts.js" type="text/javascript"></script>

    <script src="../Statics/exporting.js" type="text/javascript"></script>

    <script src="../Statics/HighChart.js" type="text/javascript"></script>

    <script type="text/javascript">

        $(function () {

            var data = [
            { name: '2013-01', group: 'olive', value: 116 },
            { name: '2013-01', group: 'momo', value: 115 },
            { name: '2013-01', group: 'only', value: 222 },
            { name: '2013-01', group: 'for', value: 324 },
            { name: '2013-02', group: 'olive', value: 156 },
            { name: '2013-02', group: 'momo', value: 185 },
            { name: '2013-02', group: 'only', value: 202 },
            { name: '2013-02', group: 'for', value: 34 },
            { name: '2013-03', group: 'olive', value: 16 },
            { name: '2013-03', group: 'momo', value: 51 },
            { name: '2013-03', group: 'only', value: 22 },
            { name: '2013-03', group: 'for', value: 84 }
            ];
            var opt = HighChart.ChartOptionTemplates.Bars(data, '','','Love-Rate', "分組柱形圖示例");
            var container = $("#container");
            HighChart.RenderChart(opt, container);
            var opt1 = HighChart.ChartOptionTemplates.Bars(data, true,'','Love-Rate', "堆積柱形圖示例");
            var container1 = $("#container1");
            HighChart.RenderChart(opt1, container1);
            var opt2 = HighChart.ChartOptionTemplates.Bars(data, '',true ,'Love-Rate', "堆積百分比柱形圖示例");
            var container2 = $("#container2");
            HighChart.RenderChart(opt2, container2);
        });
    </script>

  

 

l  展現效果

分組柱形圖

 

堆積圖

 

堆積百分比圖

 

後記:

      這裏只是列出了經常使用的一些圖表類型,若是有特殊須要的話還能夠進行自主的去抽象擴展。後續有時間的話,我也會對新的圖表類型進行擴展,還有,關於HighChart裏邊的數據下鑽的功能,這裏也沒有列出來,我的以爲這種圖表的交互,抽象出來意義不是很大,後續再看看吧,有時間的話就再試着弄弄。

相關文章
相關標籤/搜索