如何根据Highchart中的百分比给出颜色--JavaScript

时间:2017-10-16 14:13:38

标签: javascript jquery highcharts

我有一个Highchart,我会在每次点击后重建。图表值是通过查询动态创建的,我将它们推送到Chartdata array

我希望在每次查询结果后将黄色颜色赋予我最大的切片,但最大的值是每次在数组索引中更改。我该怎么办?

var chartDataArray = [
  {name:"A", y: 19},
  {name:"B", y: 49},
  {name:"C", y: 32}
];

我想总是将黄色赋予最高'y'。

Highcharts.chart('container', {
  chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie',
    style: {
      fontFamily: 'sfprodisplay',
      fontSize: '20px',
      left: '0',
      top: '0'
    }
  },

  title: {
    text: ''
  },
  credits: {
    enabled: false
  },
  exporting: {
    enabled: false
  },
  tooltip: {
    formatter: function () {
      return this.point.name + '<br/>% ' + Math.round(this.point.percentage) + '<br/>' + (this.point.custom ? this.point.custom : "")
    }
  },
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      dataLabels: {
        enabled: true,
        //format: '% {point.percentage:.0f}<br/>{point.custom}',
        formatter: function () {
          return "% " + Math.round(this.point.percentage) + "<br/>" + (this.point.custom ? this.point.custom : this.point.name)
        },
        style: {
          color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
        }
      }
    }
  },

  series: [{
    name: '',
    colorByPoint: true,
    data: chartData
  }]
});

2 个答案:

答案 0 :(得分:1)

您可以找到具有最高值的点,并在render回调函数中更新它:

var renderEnabled = true;

(...)    

events: {
  render: function() {
    if (renderEnabled) {
      var maxPoint;

      this.series[0].points.forEach(function(p) {
        if (!maxPoint || maxPoint.y < p.y) {
          maxPoint = p;
        }
      });

      renderEnabled = false; // update() calls render() - prevent infinite recursive loop by disabeling render
      maxPoint.update({
        color: 'yellow'
      });
      renderEnabled = true; // enable render() after update() is finished
    }
  }
}

实时工作演示: http://jsfiddle.net/kkulig/8ztqh0gw/

每次设置新数据时,render都会触发。

API参考:

答案 1 :(得分:0)

我通过排序数组并将颜色推送到chartDataArray来解决。

{{1}}