如何获得highcharts多个系列的总数

时间:2016-11-19 00:57:35

标签: javascript jquery date highcharts stocks

使用Highcharts value-in-legend插件http://www.highcharts.com/plugin-registry/single/10/Value-In-Legend,我已经能够实现一种多个系列总计,但我不明白如何获得点击的y轴点的总数。

例如,当我点击时,有一天我将获得3个单独的序列号,但我想以某种方式获得总数,但我只知道加载时的y点和重绘时的可见y点。我认为困难在于获得3个系列点数的总和与获得个别点的值相比。



$(function() {
  // Start the standard Highcharts setup
  var seriesOptions = [],
    yAxisOptions = [],
    seriesCounter = 0,
    names = ['MSFT', 'AAPL', 'GOOG'],
    colors = Highcharts.getOptions().colors;
  $.each(names, function(i, name) {
    $.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function(data) {
      seriesOptions[i] = {
        name: name,
        data: data
      };
      // As we're loading the data asynchronously, we don't know what order it will arrive. So
      // we keep a counter and create the chart when all the data is loaded.
      seriesCounter++;
      if(seriesCounter == names.length) {
        createChart();
      }
    });
  });
  // create the chart when all data is loaded
  function createChart() {
    $('#container').highcharts('StockChart', {
      chart: {
        events: {
          load: function(event) {
            console.log('load');
            var total = 0;
            for(var i = 0, len = this.series[0].yData.length; i < len; i++) {
              total += this.series[0].yData[i];
            }
            totalText_posts = this.renderer.text('Total: ' + total, this.plotLeft, this.plotTop - 35).attr({
              zIndex: 5
            }).add()
          },
          redraw: function(chart) {
            console.log('redraw');
            console.log(totalText_posts);
            var total = 0;
            for(var i = 0, len = this.series[0].yData.length; i < len; i++) {
              if(this.series[0].points[i] && this.series[0].points[i].visible) total += this.series[0].yData[i];
            }
            totalText_posts.element.innerHTML = 'Total: ' + total;
          }
        }
      },
      rangeSelector: {
        selected: 4
      },
      yAxis: {
        labels: {
          formatter: function() {
            return(this.value > 0 ? '+' : '') + this.value + '%';
          }
        },
        plotLines: [{
          value: 0,
          width: 2,
          color: 'silver'
        }]
      },
      legend: {
        enabled: true,
        floating: true,
        align: 'left',
        verticalAlign: 'top',
        y: 35,
        labelFormat: '<span style="color:{color}">{name}</span>: <b>{point.y:.2f} USD</b> ({point.change:.2f}%)<br/>',
        borderWidth: 0
      },
      plotOptions: {
        series: {
          compare: 'percent',
          cursor: 'pointer',
                point: {
                    events: {
                        click: function () {
                            alert('Category: ' + this.category + ', value: ' + this.y);
                        }
                    }
                }
        }
      },
      series: seriesOptions
    });
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.src.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://rawgithub.com/highslide-software/value-in-legend/master/value-in-legend.js"></script>

<div id="container" style="height: 400px; min-width: 500px"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

通过阅读Highcharts value-in-legend插件https://rawgithub.com/highslide-software/value-in-legend/master/value-in-legend.js的源代码,我找到了将总结果作为多重系列标题的方法。

&#13;
&#13;
    $(function () {
        var seriesOptions_likes = [],
            seriesCounter_likes = 0,
            names_likes = ['MSFT', 'AAPL', 'GOOG'],
            totalText_likes = 0;

        /**
         * Create the chart when all data is loaded
         * @returns {undefined}
         */
        function createLikesChart() {

            Highcharts.stockChart('container_likes', {
                chart: {

                },

                rangeSelector: {
                    selected: 4
                },

                title: {
                    text: 'Total Results: '
                },

                yAxis: {
                    labels: {
                        formatter: function () {
                            return (this.value > 0 ? ' + ' : '') + this.value + '%';
                        }
                    },
                    plotLines: [{
                        value: 0,
                        width: 2,
                        color: 'silver'
                    }]
                },

                plotOptions: {
                    series: {
                        compare: 'percent',
                        showInNavigator: true
                    }
                },

                tooltip: {
                    pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
                    valueDecimals: 2,
                    split: true
                },

                series: seriesOptions_likes,

                legend: {
                    enabled: true,
                    floating: true,
                    align: 'left',
                    verticalAlign: 'top',
                    y: 65,
                    borderWidth: 0
                },
            });
        }

        $.each(names_likes, function (i, name) {

            $.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?',    function (data) {

                seriesOptions_likes[i] = {
                    name: name,
                    data: data
                };

                // As we're loading the data asynchronously, we don't know what order it will arrive. So
                // we keep a counter and create the chart when all the data is loaded.
                seriesCounter_likes += 1;

                if (seriesCounter_likes === names_likes.length) {
                    createLikesChart();
                }
            });
        });
      });

    (function (H) {
        H.Series.prototype.point = {}; // The active point
        H.Chart.prototype.callbacks.push(function (chart) {

            $(chart.container).bind('mousemove', function () {
                var legendOptions = chart.legend.options,
                    hoverPoints = chart.hoverPoints,
                    total = 0;

                if (!hoverPoints && chart.hoverPoint) {
                    hoverPoints = [chart.hoverPoint];
                }
                if (hoverPoints) {
                    var total = 0,
                        ctr = 0;
                    H.each(hoverPoints, function (point) {
                        point.series.point = point;
                        total += point.y;

                    });
                    H.each(chart.legend.allItems, function (item) {
                        item.legendItem.attr({
                            text: legendOptions.labelFormat ?
                                H.format(legendOptions.labelFormat, item) :
                                legendOptions.labelFormatter.call(item)
                        });
                    });

                    chart.legend.render();

                    chart.title.update({ text: 'Total Results: ' + total.toFixed(2) });
                }
            });
        });
        // Hide the tooltip but allow the crosshair
        H.Tooltip.prototype.defaultFormatter = function () { return false; };
    }(Highcharts));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>

<div id="container_likes" style="height: 400px; min-width: 600px"></div>
&#13;
&#13;
&#13;