美文网首页
2018-09-10 好看的图表插件

2018-09-10 好看的图表插件

作者: 土豆丝炒洋芋丝 | 来源:发表于2018-09-10 15:47 被阅读0次

    https://www.hcharts.cn/ 插件网址
    不会用。。。看不懂 在网上找到了 一个好心人
    这是他自己整理的 http://www.cnblogs.com/Olive116/p/3777021.html 原文地址
    我搬过来 自己归纳了一下 用ajax实现了一下

    使用时的注意事项: data里面的 name和value 如果要修改 连着HighChart.js里面对应的也要修改

    HighChart.js
    
    //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);
        }
    };
    

    具体的页面展示
    饼 图

    <!-- 饼 图 饼 图 饼 图 饼 图 -->
    <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>
    

    折线图

    <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>
    

    柱形图

    <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>
    

    折线图实例
    很奇怪的事
    HTML视图页面的名字叫 index.html controller里面没有这个index方法
    ajax 请求devTraDynamic 这个方法 然后ajaxReturn 就好了 柱状图也是这样的做法

    <div id="containers" style="min-width:300px;height:400px"></div>
          <script type="text/javascript">
    
           $(function () {
              function test () {
                  $.ajax({
                      type:"post",
                      async:false,
                      url:'{:U("Tra/devTraDynamic")}',
                      data:{},
                      dataType:"json",
                      success:function(res){
                          console.log(res);
                          var data = res;
                          var opt = HighChart.ChartOptionTemplates.Line(res, '经过人数', "人流监测图");
                          var container = $("#containers");
                          HighChart.RenderChart(opt, container);
    
                      }
                  });
    
                  setTimeout(test, 60000);
              }
              test();
           });
    
       </script>
    

    $result数据格式如下 value指向的值 必须为整数型 即不带单引号 折线图柱状图都是一样

    <?php
    /**
        * 设备附近人流量动态图
        * @return   json
        */
      public function devTraDynamic()
      {
          $sql = 
              'SELECT 
                  count(t.mac) AS value,
                  FROM_UNIXTIME(UNIX_TIMESTAMP((FLOOR(FROM_UNIXTIME(t.col_time) / 100) * 100))) AS name
              FROM 
              (
                  SELECT 
                      col_time, 
                      mac
                  FROM '.C('DB_NAME_PREFIX').'devices_tra'.' 
                  WHERE 
                      col_time BETWEEN UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 HOUR)) AND UNIX_TIMESTAMP(NOW())
                  GROUP BY 
                      mac
              ) AS t 
              GROUP BY FLOOR(FROM_UNIXTIME(t.col_time) / 100) * 100
              ORDER BY t.col_time ASC';
          $result = M()->query($sql);
          foreach ($result as $key => $val) {
              $result[$key]['value'] = (int)($val['value']);
              $result[$key]['name'] = strrchr(($val['name']),' ');
              // strrchr() 函数查找字符串在另一个字符串中最后一次出现的位置,并返回从该位置到字符串结尾的所有字符。
          }
          $this->ajaxReturn($result);
                 // $result数据格式如下 value指向的值 必须为整数型 即不带单引号
                 // $result = array(
                      // array('value'=>12,'name'=>'12:00:00'),
                      // array('name'=>'12:01:00','value'=>22),
                      // array('name'=>'12:02:00','value'=>13),
                      // array('name'=>'12:03:00','value'=>20),
                      // array('name'=>'12:04:00','value'=>34),
                      // array('name'=>'12:05:00','value'=>23),
                      / array('name'=>'12:24:00','value'=>12)
                  // ); 
       }
    ?>
    

    柱状图实例

    <div id="containerY" style="min-width:300px;height:400px"></div>
      <script type="text/javascript">
           $(function () { alert(666);
              function test () {
                  $.ajax({
                      type:"post",
                      async:false,
                      url:'{:U("Now/devTraDynamic")}',
                      data:{},
                      dataType:"json",
                      success:function(res){
                          console.log(res);
                          var data = res;
                          var opt = HighChart.ChartOptionTemplates.Bars(data, '','','Love-Rate', "分组柱形图示例");
                          var container = $("#containerY");
                          HighChart.RenderChart(opt, container);
                      }
                  });
                  setTimeout(test, 86400000);
              }
              test();
           });
    
       </script>
    
    public function devTraDynamic() {
    
           $pasttime = strtotime("-1 day"); // 当前时间的前24个小时
           $presenttime = time(); // 当前时间
           $sql = " SELECT 
                       HOUR(FROM_UNIXTIME(col_time)) as name, 
                       AVG(aqi) as value
                   FROM  ped_devices_env
                   WHERE  col_time BETWEEN $pasttime AND $presenttime
                   GROUP BY HOUR( FROM_UNIXTIME(col_time))";
           $result = M()->query($sql); 
           foreach ($result as $key => $val) {
               $result[$key]['name'] = $val['name'].':00';
               $result[$key]['group'] = '空气质量 aqi';
               $result[$key]['value'] = (int)($val['value']);
           }
           file_put_contents('./Application/Runtime/sqlyz123.txt', var_export($result ,true));
           $this->ajaxReturn($result);
    
       }
       // $result 的数据结构 同样的是 value只能是整数类型 不带单引号的那种 不然图显示不出来的
       public function alldata() {
          $data = array(
                      array('name'=>'9-3','group'=>'空气质量','value'=>12),
                      array('name'=>'9-4','group'=>'空气质量','value'=>121),
                      array('name'=>'9-5','group'=>'空气质量','value'=>124),
                      array('name'=>'9-6','group'=>'空气质量','value'=>145),
                      array('name'=>'9-7','group'=>'空气质量','value'=>65)
                  );
          $this->ajaxReturn($data);
       }
    

    相关文章

      网友评论

          本文标题:2018-09-10 好看的图表插件

          本文链接:https://www.haomeiwen.com/subject/wljsgftx.html