如何根据值更改饼图颜色

时间:2018-09-25 13:27:01

标签: javascript jquery model-view-controller highcharts

我想在View Bag = Inactive时显示红色,我使用高图表显示饼图。状态为活动时,应为默认值或蓝色;状态为不活动时,应为红色

enter image description here

代码

Highcharts.chart('container', {
  chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
  },
  title: {
    text: 'Transformers status'
  },
  tooltip: {
    pointFormat: '{series.name} <b>{}</b>'
  },
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      dataLabels: {
        enabled: true,
        format: '<b>{point.name} @ViewBag.status</b> {}',
        style: {
          color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
        }
      }
    }
  },
  series: [{
    name: '@ViewBag.status',
    colorByPoint: true,
    data: [{
      name: 'FP N-67.7',
      y: 1,
      sliced: true,
      selected: true
    }]
  }]
});
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container" style="height: 400px"></div>

1 个答案:

答案 0 :(得分:0)

根据我对您问题的理解,可以采用两种方法:

  1. 如果启用/停用标记是静态的(即,一旦加载了屏幕,它就不会更改)

您可以设置文档的颜色属性onload:

Highcharts.setOptions({
      colors: ['#ff0000']
});
  1. 如果在加载后某些事件上标志可以更改::在这种情况下,您可以使用chart变量来更改图形的颜色。

    chart.series [0] .data [0] .graphic.attr({fill:'#ff0000'});

在下面的示例中,我试图涵盖这两个用例。希望这会有所帮助

$(function() {
  if ($("input[name='status']:checked").val() == 'inactive') {
    Highcharts.setOptions({
      colors: ['#ff0000']
    });
  }
  var chart;
  $(document).ready(function() {
    chart = new Highcharts.Chart({
      chart: {
        renderTo: 'container',
      },
      plotOptions: {
        pie: {
          allowPointSelect: true,
          cursor: 'pointer'
        }
      },
      series: [{
        type: 'pie',
        name: 'Browser share',
        data: [
          ['Chrome', 75]
        ]
      }]
    });
  });
  $("input[type='radio']").click(function() {
    var radioValue = $("input[name='status']:checked").val();
    if (radioValue == 'inactive') {
      chart.series[0].data[0].graphic.attr({
        fill: '#ff0000'
      });
    } else {
      chart.series[0].data[0].graphic.attr({
        fill: '#2f7ed8'
      });
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>

<label><input type="radio" name="status" value="active">Active</label>
<label><input type="radio" name="status" value="inactive" checked>In-Active</label>

<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>