根据值改变chart.js中的条形图颜色

Change bar color in chart.js depending on value

本文关键字:条形图 颜色 js chart 改变      更新时间:2023-09-26

我想使用chart.js (www.chartjs.org)创建一个条形图。条填充颜色应该根据值而变化。

当值小于10时,颜色为绿色,11-15为黄色,16-20为红色。

是否有可能与chart.js,以及如何做到这一点?

Chartjs实际上允许background-color是一个数组,因此您可以根据需要提供一个颜色数组。这意味着您可以在创建数据集的地方创建颜色。在我自己的例子中,我没有这样做:

    backgroundColor: [
        <?=$color?>
        ],
    data: [
        <?=$tableData;?>
    ],

其中$color类似于'rgba(0,255,0,1)','rgba(255,0,0,1)',, $tableData类似于1,-1

我使用php从服务器推送数据,但是如果你想在JavaScript中做一些事情,下面的示例可能会帮助你。

这是设置Chartjs图表中每个条的颜色的正确方法。

我在上面的链接上从NanYu那里得到了下面的样本。

var chartColors = {
  color1: 'rgba(77, 166, 255, 0.5)',
  color2: 'rgba(218, 165, 32, 0.5)',
  color3: 'rgba(175, 0, 42, 0.5)'
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['value 1', 'value 2', 'value 3', 'value 4'],
    datasets: [{
      label: 'Dataset 1',
      backgroundColor: [
        chartColors.color1,
        chartColors.color1,
        chartColors.color1,
        chartColors.color1
      ],
      data: [29, 57, 65, 42]
    }],
  }
});
var colorChangeValue = 50; //set this to whatever is the deciding color change value
var dataset = myChart.data.datasets[0];
for (var i = 0; i < dataset.data.length; i++) {
  if (dataset.data[i] < 30) {
    dataset.backgroundColor[i] = chartColors.color1;
  }
  else if ((dataset.data[i] > 31) && (dataset.data[i] <= 60)){
    dataset.backgroundColor[i] = chartColors.color2;
  }
  else{
   dataset.backgroundColor[i] = chartColors.color3;
  }
}
myChart.update();

非常老的帖子,但对于从谷歌搜索到这里的人来说,用ChartJS做这件事的一种方法。

您可以将您的数据转换为2个数据集:
-第一个用正值,用0代替所有的负值
- 2用负值,用0

代替所有的正值
originalSet = [1,-1, 3,-3, 5]
positiveSet = [1, 0, 3, 0, 5]
negativeSet = [0,-1, 0,-3, 0]

然后只需为每组添加您选择的颜色:

datasets: [
  { data: positiveSet, backgroundColor: 'rgba(0,255,0,0.5)' },
  { data: negativeSet, backgroundColor: 'rgba(255,0,0,0.5)' }
]

此方法不仅可以应用于正/负分离,还可以在一般情况下应用于基于值的样式。

我从未使用过chart.js,但这是我的建议…

Chart.defaults.global = { //this has all the information for the chart, I just removed everything else
    // String - Colour of the scale line
    scaleLineColor: "rgba(0,0,0,.1)"
}

我会输入....

if (number < 10) { Chart.defaults.global.scaleLineColor = "rgba(whatever)" } 

然后用你所有的代码填充它。希望这对你有帮助!

我没有找到使用chart.js的方法,并切换到谷歌可视化。

可以这样做:

 // first index in chartData array describes the fields in the following indexes,
 // The first two are the X and Y values, role: style tells the chart to use the third
 // field as the style of that particular bar. role: annotation tells the chart to 
 // add the contents of the fourth field as a label to each bar.
 var chartHeader = [['Time', 'Measurement', { role: 'style' }, { role: 'annotation' }]];
 function ConvertJsonToChartData(json) {
        var chartData = chartHeader;
        for (var key in json) {
            var x = json[key].X;
            var elapsedTime = json[key].ElapsedTime;
            // set style based on value of elapsedTime
            var style = 'black';
            if (elapsedTime > GlobalSettings['criticalThreshold']) {
                style = GlobalSettings['criticalColor'];
            } else if(elapsedTime > GlobalSettings['warningThreshold']) {
                style = GlobalSettings['warningColor'];
            }
            // add a new datapoint to the chart
            chartData.push([x, elapsedTime, style, elapsedTime]);
        }
        return chartData;
    }
    function MakeHourGraph(json) {
        var chartData = ConvertJsonToChartData(json);
        var data = google.visualization.arrayToDataTable(chartData);
        var options = {
            title: 'Response Times',
            hAxis: { title: 'Hour', titleTextStyle: { color: 'blue' } },
            vAxis: { title: 'msecs', titleTextStyle: { color: 'blue' } },
            legend: { position: "none" }
        };
        var chart = new google.visualization.ColumnChart(document.getElementById('hour_chart_div'));
        chart.draw(data, options);
    }