ChartJS - Different color per data point

Xander picture Xander · Jan 26, 2015 · Viewed 42.8k times · Source

Is there a way to set a different color to a datapoint in a Line Chart if its above a certain value?

I found this example for dxChart - https://stackoverflow.com/a/24928967/949195 - and now looking for something similar for ChartJS

Answer

JIntro picture JIntro · Sep 2, 2016

In updating to version 2.2.2 of ChartJS, I found that the accepted answer no longer works. The datasets will take an array holding styling information for the properties. In this case:

var pointBackgroundColors = [];
var myChart = new Chart($('#myChart').get(0).getContext('2d'), {
    type: 'line',
    data: {
        datasets: [
            {
                data: dataPoints,
                pointBackgroundColor: pointBackgroundColors
            }
        ]
    }
});

for (i = 0; i < myChart.data.datasets[0].data.length; i++) {
    if (myChart.data.datasets[0].data[i] > 100) {
        pointBackgroundColors.push("#90cd8a");
    } else {
        pointBackgroundColors.push("#f58368");
    }
}

myChart.update();

I found this looking through the samples for ChartJS, specifically this one: "Different Point Sizes Example"