条形图中的条形颜色是否可以根据其值而变化? [英] Can the colors of bars in a bar chart be varied based on their value?

查看:59
本文介绍了条形图中的条形颜色是否可以根据其值而变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用chart.js 2,可否根据其值改变条车中条形的颜色?

Using chart.js 2, can the colors of the bars in a bar-cart be varied based on their value?

例如,如果比例为0 -100,具有50%或以上的列可能是绿色,而0-49%的列可能是红色。

For example, if the scale is 0 - 100, columns with 50% and above could be green, while 0-49% could be red.

推荐答案

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

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>

这篇关于条形图中的条形颜色是否可以根据其值而变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆