ritwick_ _D
ritwick_ _D

Reputation: 127

How do I use customColor in ngx-charts to change the graph color according to data value?

I am unable to use the customColor attribute to change the color of some of my datapoints dynamically. I am using ngx-charts. I followed the docs, but my colors didnt change. Here is my code:

lineCustomColor() {
for (let i = 0; i < multi[0].series.length; i++) {
  if (multi[0].series[i].value > 40000000) {
    this.result.push({ name: multi[0].series[i].name, value: '#7aa3e0' });
  }
  // else {
  //   this.result.push({ name: multi[0].series[i].name, value: '#33cc33' });
  // }
}

And in my template file:

<ngx-charts-line-chart
  [view]="view"
  [legend]="legend"
  [showXAxisLabel]="showXAxisLabel"
  [scheme]="colorScheme"
  [showYAxisLabel]="showYAxisLabel"
  [xAxis]="xAxis"
  [yAxis]="yAxis"
  [xAxisLabel]="xAxisLabel"
  [yAxisLabel]="yAxisLabel"
  [timeline]="timeline"
  [results]="data"
  [animations]="false"
  [customColors]="lineCustomColor()"
  [scheme]="colorScheme"
>
</ngx-charts-line-chart>

On uncommenting my else, it does not work. Even if I pass an object to [customColors], not a function, then also my color does not change according to the data point. Any help would be greatly appreciated.

Upvotes: 1

Views: 2522

Answers (1)

Pepe Roman Valdiviezo
Pepe Roman Valdiviezo

Reputation: 11

I hope it works for you.

IN: (ngx-charts: "20.1.0")

HTML template

<ngx-charts-bar-horizontal
              [view]="view"
              [scheme]="colorScheme"
              [results]="multi"
</ngx-charts-bar-horizontal>

Component.ts

import { Color, ScaleType } from '@swimlane/ngx-charts';
     
//Data
  multi: any[] = 
  [
    {
      "name": "Antelectasis",
      "value": 10
    },
    {
      "name": "Consolidation",
      "value": 25
    },
    {
      "name": "Infiltration",
      "value": 90
    }
  ]

  backgroundColor:any[] = [];

  //Custom Color
  myColors(){ 
    const rojo = "rgb(255, 0, 0)";
    const verde = "rgb(0, 255, 14)";
    const amarillo = "rgb(255, 242, 0)";

    this.multi.forEach( disease =>{
      if( disease.value >= 51 ){
        this.backgroundColor.push(rojo);
      }else if(disease.value >= 21 && disease.value <= 50){
        this.backgroundColor.push(amarillo);
      }else{
        this.backgroundColor.push(verde);
      }
    });

  }

  // Apply Color
  colorScheme: Color = {
    name: 'Variation',
    selectable: true,
    group: ScaleType.Ordinal,
    domain: this.backgroundColor
  };

  ngOnInit(): void {
    this.myColors();
  }

Upvotes: 1

Related Questions