Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Ngx-Charts customColor function

Tags:

ngx-charts

How do you use the customColor attribute as a function? I'm looking to build a scatter plot and mark all points with a negative value as red, and all those with a positive value as green. I would think that the customColor functionality would let me do this, but I've only seen examples of customColor as an object rather than a function. Thanks!

like image 369
K Gardner Avatar asked Jun 08 '18 17:06

K Gardner


2 Answers

HTML template

<ngx-charts-bar-vertical
      [animations]="barAnimations"
      [customColors]="barCustomColors()"
      ...
</ngx-charts-bar-vertical>

Component

...
   barAnimations = false;
   barSingle = [
      {"name": "56","value": 654},
      {"name": "57","value": 123},
      ...
   ]

   constructor() {}

   ngOnInit() {}

   // your custom function
   // make sure return structure is array like
   // [
   //    {"name": "a","value": "#ff0000"},
   //    {"name": "b","value": "#ff0000"}
   // ]   
   barCustomColors() {
      let result: any[] = [];
      for (let i = 0; i < this.barSingle.length; i++) {
         if (this.barSingle[i].value < 200) {
            result.push({"name": this.barSingle[i].name,"value": "#0000ff"});
         }
      }
      return result;
   }
...

Then the chart will call the function when chart was created.

Make sure the custom function is return the array and include name and value of color. It is like:

[
   {"name": "a","value": "#ff0000"},
   {"name": "b","value": "#ff0000"}
]

But if the animations mode is on, it will call the function too many time and make the issue below.

requestAnimationFrame handler took ms

It will make your chart drawing too slow. So if you want to use function to control and custom your chart color. Suggest closing the animations mode.

like image 158
許聖泉 Avatar answered Sep 23 '22 02:09

許聖泉


You need to pass a prepared array of colors instead of a function

setCustomColors() {
    let result: any[] = [];
    for (let i = 0; i < this.barSingle.length; i++) {
       if (this.barSingle[i].value < 200) {
          result.push({"name": this.barSingle[i].name,"value": "#ff0000"});
       }
       else{
          result.push({"name": this.barSingle[i].name,"value": "#33cc33"});
       }
    }
    return result;
 }
 customColors: any;

and set the value on component creation

constructor() { 
    this.customColors = this.setCustomColors();
  }
like image 27
Dominik Brázdil Avatar answered Sep 24 '22 02:09

Dominik Brázdil