且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

条形图中的条形颜色是否可以根据其值而变化?

更新时间:2023-11-26 23:36:58

我知道对于每个绘制的点都没有配置或回调。我能想到的***方法是创建一个可以修改图表配置/数据对象的函数。这不是解决问题的最优雅的方法,但是可以。

As far as I know there is no configuration or callback for each individual point being drawn. The best way I can think of to do this would be to create a function that would modify your chart config/data object. This isn't the most elegant way to deal with the problem, but it would work.

将图表配置/数据对象传递给将添加背景色的函数。

Pass your chart config/data object to a function that will add the background color.

该示例的要点是 function AddBackgroundColors(chartConfig)

示例:

function AddBackgroundColors(chartConfig) {
  var min = 1; // Min value
  var max = 100; // Max value
  var datasets;
  var dataset;
  var value;
  var range = (max - min);
  var percentage;
  var backgroundColor;

  // Make sure the data exists
  if (chartConfig &&
    chartConfig.data &&
    chartConfig.data.datasets) {
    // Loop through all the datasets
    datasets = chartConfig.data.datasets;
    for (var i = 0; i < datasets.length; i++) {
      // Get the values percentage for the value range
      dataset = datasets[i];
      value = dataset.data[0];
      percentage = value / range * 100;

      // Change the background color for this dataset based on its percentage
      if (percentage > 100) {
        // > 100%
        backgroundColor = '#0000ff';
      } else if (percentage >= 50) {
        // 50% - 100%
        backgroundColor = '#00ff00';
      } else {
        // < 50%
        backgroundColor = '#ff0000';
      }
      dataset.backgroundColor = backgroundColor;
    }
  }

  // Return the chart config object with the new background colors
  return chartConfig;
}

var chartConfig = {
  type: 'bar',
  data: {
    labels: ["percentage"],
    datasets: [{
      label: '100%',
      data: [100]
    }, {
      label: '50%',
      data: [50]
    }, {
      label: '49%',
      data: [49]
    }, {
      label: '5%',
      data: [5]
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
};

window.onload = function() {
  var ctx = document.getElementById("canvas").getContext("2d");
  chartConfig = AddBackgroundColors(chartConfig);
  var myChart = new Chart(ctx, chartConfig);
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.2/Chart.bundle.min.js"></script>
<canvas id="canvas" width="400" height="200"></canvas>