如何使用Chart.js更改Barchart中仅一列的颜色

时间:2014-11-07 11:20:54

标签: javascript colors charts chart.js

JS

http://www.chartjs.org/docs/#bar-chart

我正在使用基本样本:

HTML

<canvas id="canvas" height="450" width="600"></canvas>

JS

var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        }
    ]
};

window.onload = function(){
    var ctx = document.getElementById("canvas").getContext("2d");
    window.myBar = new Chart(ctx).Bar(data, {
         responsive : true
    });
}

我想改变一列的颜色。我该怎么做?我尝试了很多次教程,但我没有找到解决方案。你能救我吗?

2 个答案:

答案 0 :(得分:0)

你可以改变这样的颜色。这是jsfiddle

var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        }
    ]
};
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx).Bar(data);

// change color of first bar
myChart.datasets[0].bars[0].fillColor = "rgba(255,0,0,1)";
myChart.update();

答案 1 :(得分:0)

目前,您可以将backgroundColor指定为每个数据集记录的颜色数组:

{ datasets: [{
                label: t('Dataset with last column red'),
                backgroundColor: graphData.length
                  ? [...new Array(calculatedGraphData.length - 1).fill('#ff0000'), '#ff0000']
                  : '#ff0000',
                data: graphData,
              }] }