ChartJS - Different color per data point
Asked Answered
S

8

46

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://mcmap.net/q/373116/-changing-color-of-specific-chartjs-point - and now looking for something similar for ChartJS

Sciuroid answered 26/1, 2015 at 22:4 Comment(2)
There's a solution for the radius's size at https://mcmap.net/q/373117/-highlight-a-particular-point-in-chart-js that might be useful for this case as well.Addy
For recent versions of chart.js, you can achieve this by setting pointBackgroundColor to an array of colours (one per point), OR - more flexibly - by setting it to a function that sets the colour according to the context. For an example see my answer below (Nov 2019)Counterespionage
J
10

For chartjs 2.0 see this following answer.

Original answer below.


Good question regarding ChartJS. I've been wanting to do a similar thing. i.e dynamically change the point colour to a different colour. Have you tried this below. I just tried it and it worked for me.

Try this:

myLineChart.datasets[0].points[4].fillColor =   "rgba(000,111,111,55)" ; 

Or Try this:

myLineChart.datasets[0].points[4].fillColor =  "#FF0000";

Or even this:

myLineChart.datasets[0].points[4].fillColor =  "lightgreen";

Then do this:

myLineChart.update();

I guess you could have something like;

if (myLineChart.datasets[0].points[4].value > 100) {
    myLineChart.datasets[0].points[4].fillColor =  "lightgreen";
    myLineChart.update();
 }

Give it a try anyway.

Jackiejackinoffice answered 31/1, 2015 at 12:20 Comment(2)
I should've mentioned that I'm using this plugin in AngularJS application: carlcraig.github.io/tc-angular-chartjs But the code above, did let me get it done through setting up the usual way as per ChartJS documentation.Sciuroid
for me it is not showing points key itself, i don't know why? Need some help?Mccandless
B
50

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"

Borghese answered 2/9, 2016 at 14:59 Comment(1)
To control the point's border color, use the same approach, but with the pointBorderColor property.Storms
C
39

With recent versions of chart.js I would recommend doing this with scriptable options.

Scriptable options give you an easy way to vary the style of a dataset property (e.g. line point colour) dynamically according to some function you provide. Your function is passed a 'context' object that tells it the index and value of the point etc. (see below).

Most chart properties can be scripted; the dataset properties for each chart type tell you the exact list (e.g. see here for line chart).

Here is how you might use scriptable options on a line chart (based on the example in the docs). On this chart negative data points are shown in red, and positive ones in alternating blue/green:

window.myChart = Chart.Line(ctx, {
    data: {
        labels: x_data,
        datasets: [
            {
                data: y_data,
                label: "Test Data",
                borderColor: "#3e95cd",
                fill: false,
                pointBackgroundColor: function(context) {
                    var index = context.dataIndex;
                    var value = context.dataset.data[index];
                    return value < 0 ? 'red' :  // draw negative values in red
                        index % 2 ? 'blue' :    // else, alternate values in blue and green
                            'green';
                }
            }
        ],
    }
});

The context object passed to your function can have the following properties. Some of these won't be present for certain types of entity, so test before use.

  • chart: the associated chart
  • dataIndex: index of the current data
  • dataset: dataset at index datasetIndex
  • datasetIndex: index of the current dataset
  • hover: true if hovered
Counterespionage answered 30/11, 2019 at 18:59 Comment(3)
Thanks This works perfectly for me. But in case I want to draw the line with different color instead of the points in different color - as per the current value - where should I be making the changes?Hesperidium
Take a look at the documentation for charts -> line -> dataset properties ... you will see that you can style the line with backgroundColor and borderColor, which are also scriptable optionsCounterespionage
Belated apologies @Hesperidium - doing the line in different colours is more complicated than I thought. It's still possible though: have a look at #68778968Counterespionage
A
15

Here's what worked for me (v 2.7.0), first I had to set pointBackgroundColor and pointBorderColor in the dataset to an array (you can fill this array with colours in the first place if you want):

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [
            {
                data: dataPoints,
                pointBackgroundColor: [],
                pointBorderColor: [],
            }
        ]
    }
});

Then you can monkey with the colours of the points directly:

  myChart.data.datasets[0].pointBackgroundColor[4] = "#cc00cc";
  myChart.data.datasets[0].pointBorderColor[4] = "#cc0000";
  myChart.update();

Some other properties to play with to distinguish a point: pointStrokeColor (it apparently exists but I can't seem to get it to work), pointRadius & pointHoverRadius (integers), pointStyle ('triangle', 'rect', 'rectRot', 'cross', 'crossRot', 'star', 'line', and 'dash'), though I can't seem to figure out the defaults for pointRadius and pointStyle.

Acyl answered 13/10, 2017 at 15:31 Comment(1)
myChart.data.datasets[0].pointBorderColor[4] = "#cc0000"; its giving error (undefine) for me & myChart.data.datasets[0].pointBorderColor = "#cc0000"; change all points color & not particular points. is there anyone knows how to change particular points color ?Gooseberry
J
10

For chartjs 2.0 see this following answer.

Original answer below.


Good question regarding ChartJS. I've been wanting to do a similar thing. i.e dynamically change the point colour to a different colour. Have you tried this below. I just tried it and it worked for me.

Try this:

myLineChart.datasets[0].points[4].fillColor =   "rgba(000,111,111,55)" ; 

Or Try this:

myLineChart.datasets[0].points[4].fillColor =  "#FF0000";

Or even this:

myLineChart.datasets[0].points[4].fillColor =  "lightgreen";

Then do this:

myLineChart.update();

I guess you could have something like;

if (myLineChart.datasets[0].points[4].value > 100) {
    myLineChart.datasets[0].points[4].fillColor =  "lightgreen";
    myLineChart.update();
 }

Give it a try anyway.

Jackiejackinoffice answered 31/1, 2015 at 12:20 Comment(2)
I should've mentioned that I'm using this plugin in AngularJS application: carlcraig.github.io/tc-angular-chartjs But the code above, did let me get it done through setting up the usual way as per ChartJS documentation.Sciuroid
for me it is not showing points key itself, i don't know why? Need some help?Mccandless
F
1

Just adding what worked for me in the new 2.0 version.

Instead of:

myLineChart.datasets[0].points[4].fillColor =  "lightgreen";

I had to use:

myChart.config.data.datasets[0].backgroundColor[4] = "lightgreen";

Not sure if that's because of a change in 2.0 or because I'm using a bar chart and not a line chart.

Fauch answered 3/6, 2016 at 15:37 Comment(0)
S
1

For the new version in ChartJS, I found that you can specify every point information by adding a list of attributes with the data set, here is an example to make the last point with red color and the first 3 points with different point sizes:

datasets: [{ 
        data: JSON.parse("{{week_visits|escapejs}}"),
        label: "Visitors",
        borderColor: "#71b9ac",
        fill: false,
        backgroundColor: "#dab193",
        pointStyle: 'circle',
        pointRadius: [7,6,5,5,5,5,5],
        pointHoverRadius: [9,8,7,7,7,7,7],
        pointBackgroundColor: ['red','#dab193','#dab193','#dab193','#dab193','#dab193','#ffffff'],
    },  

Look at the pointRadius, pointHoverRadius, and pointBackgroundColor, all have the same list size but every data with the same index '7 for 9 for red, 6 for 8 for $dab193' will be together as a point attribute.

Note: this code from Django templets, gets the data from views.py in JSON format.

Sicard answered 24/10, 2023 at 7:41 Comment(0)
T
0

If you initialize the myChart in this manner,

var myChart = new Chart(ctx, {
  type: 'line',
  data: {

you have to change line color by this code

  myChart.data.datasets[0].backgroundColor[0] ="#87CEFA";

If you initialize the myChart in this manner,

myBar = new Chart(ctx).Line(barChartData, {

you have to change line color by this code

myLineChart.datasets[0].points[4].fillColor =  "#FF0000";
Toper answered 22/9, 2017 at 4:3 Comment(1)
2.7.3 here, and there's no .points structure in the Chart object.Forerun
O
0

most of the ways were too complex for me so here's how is solved it: I am using react btw, so in the data parameter i was doing this

Before:

datasets:[
        {
            label: 'Maximum Predicted Temperature',
            fill: false,
            lineTension: 0.5,
            backgroundColor: ['red'],
            borderColor: 'rgba(0,0,0,1)',
            borderWidth: 2,
            data: max
        },

After:

datasets:[
        {
            label: 'Maximum Predicted Temperature',
            fill: false,
            lineTension: 0.5,
            backgroundColor: ['red','blue','green','yellow','orange','purple','pink','brown','grey','black','white','violet'],
            borderColor: ['red','blue','green','yellow','orange','purple','pink','brown','grey','black','white','violet'],
            borderWidth: 2,
            data: max
        }

the color will loop if your given data points are more than the number of colors provided and the color red will apply on every 12th data point it really helped me thought the solution is bit clumsy but gives more control hope this helps

Oriole answered 11/3, 2023 at 14:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.