7

I want to change the style of a single point in my Chart.js graph. I tried the solutions here

ChartJS - Different color per data point

But none of them work for me. For example, to change the background color of the 4th point in my first dataset, I would try the following 2 solutions (and also removing/adding .config):

myChart.config.data.datasets[0].points[4].pointBackgroundColor = 'red';
myChart.config.data.datasets[0].pointBackgroundColor[4] = "red";
myChart.update();

to no effect. On the contrary, changing the style of the entire dataset works perfectly fine:

myChart.config.data.datasets[0].pointBackgroundColor = 'lightgreen';
myChart.update();

jsfiddle: https://jsfiddle.net/e8n4xd4z/15766/; Why is this?

agreis1
  • 1,021
  • 5
  • 13
  • 17

1 Answers1

10

https://jsfiddle.net/e8n4xd4z/15822/

You can use an array of colors to the pointBackgroundColor in the options as follows

pointBackgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]

Then if you want to change any individual point color later you can do that as follows

myChart.config.data.datasets[0]['pointBackgroundColor'][4] = 'red';

I have attached the link to the updated jsfiddle. You can check that. Cheers!

simplelenz
  • 877
  • 1
  • 9
  • 22
  • Your array method works, but when working with ~100 points (all the same color before changing one individual point's color), do you know of a way to set the original array of colors without having it look like `['Red', 'Red', 'Red', 'Red', ...]`? – agreis1 Aug 21 '18 at 17:46
  • can you write a simple for loop to initialize the array elements to a single color? – simplelenz Aug 21 '18 at 18:00
  • Yeah, a tad ugly but it works fine. Thank you for your help! – agreis1 Aug 21 '18 at 18:10
  • Yeah. According to chart.js documentation, for the `pointBackgroundColor` you can pass either a color or an array of colors. If you just pass a color, then you can't access it using indexes like we do with arrays. Glad I could help. – simplelenz Aug 21 '18 at 18:15
  • You can also use the .fill() function to initialize an array to a static value. https://www.w3schools.com/jsref/jsref_fill.asp – killer_kohlrabi Jan 14 '20 at 16:00