Search code examples
angularchart.jsng2-chartsngx-charts

How to have custom colors in ng2-charts and chart.js according to data?


I'm looking to build a line graph and mark all points above a certain value as red, and all those below that value as blue. I tried doing so with ngx-chart but that did not work. How do I do so with ng2-charts? Is that even possible? Any help would be greatly appreciated.


Solution

  • You can define the option pointBackgroundColor on the dataset as an array of colors for each point. To do so, you could use Array.map() as follows:

    pointBackgroundColor: this.data.map(v => v > 60 ? "red" : "blue"),
     
    

    This basically draws red points for values above 60, blue points otherwise.

    Please take a look at this CodeSandbox and see how it works.