动态定义饼图中的颜色数据

Define colors in pie chart dynamically data

我想根据 JSON 文件包含的内容不断定义饼图中每个切片的颜色。因此,如果 JSON 文件是 op = [{name: "Idle", y: 3},{name: "Overload", y: 7}] 但有时它也会不断变化,则格式数据始终包含 string(name : Busy/Overload/Idle) 和 int( y ).

我尝试了不同的方法,其中之一:

ngOnInit() {
 this.indicatorservice.getIndicator().subscribe((res)=>{
  this.indicator = res;
  let op = this.indicator.map(e=>{
    let key = Object.keys(e)[0]
    return { name: key, y: +e[key] }
  })
  op.forEach(element => {
    if (element.name == 'Busy') {
      this.colorVal = '#ffff00';
    }
    if (element.name == 'Idle') {
      this.colorVal = '#008000';
    }
    if (element.name == 'Overload') {
      this.colorVal = '#ff0000';
    }
  });
  setTimeout( ()=>{
    this.Highcharts.chart({
      chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie',
        renderTo:'container',
      },
      title: {
        text: 'Todays Shift Indicator'
      },
      tooltip: {
          pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
      },
      plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: true,
                format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                style: {
                    color: 'white'
                }
            }
        }
      },
      series: [{
        name: 'Brands',
        colorByPoint: true,
        data: op,
        color: this.colorVal
      }]

   })},300);
 })
}

动态采样数据:

op : [{name: "Idle", y: 3},{name: "Overload", y: 7},{name: "Busy", y: 2}]

or sometimes...

op : [{name: "Idle", y: 3},{name: "Overload", y: 7}]

etc.

但不幸的是,它不起作用。

如有任何帮助,我们将不胜感激。谢谢

您需要在点级别设置颜色:

    op.forEach(element => {
        if (element.name == 'Busy') {
            element.color = '#ffff00';
        }
        if (element.name == 'Idle') {
            element.color = '#008000';
        }
        if (element.name == 'Overload') {
            element.color = '#ff0000';
        }
    });

现场演示:http://jsfiddle.net/BlackLabel/850wx1L3/

API参考:https://api.highcharts.com/highcharts/series.pie.data.color