0

I am building a chart.js function in my angular2 web application. I want the bars in a bar chart to be red or green depending if their value is above or below a certain threshold. At the moment, I have a static solution which looks like this:

  public barChartLabels: string[] = ['06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '00:00', '01:00', '02:00', '03:00', '04:00', '05:00'];
  public barChartType: string = 'bar';
  public barChartLegend: boolean = false;

  public barChartData: any[] = [
    {
      data: [85, 81, 80, 81, 56, 73, 70, 5, 0, 0, 65, 70, 83, 90, 85, 86, 84, 80, 87, 88, 82, 74, 71, 80],
      label: 'Values'
    }
  ];
private colors = [
    {
      backgroundColor: [
        'rgba(45, 227, 81, 0.2)',
        'rgba(45, 227, 81, 0.2)',
        'rgba(45, 227, 81, 0.2)',
        'rgba(45, 227, 81, 0.2)',
        'rgba(45, 227, 81, 0.2)',
        'rgba(45, 227, 81, 0.2)'
        // Potentially loads more colors
      ]
    }
  ];

However, this is messy and feels like overkill. I need a solution which will support the dynamic update of my data and simply compare the value to a threshold and return one or the other color. This has to be done in a way that I can bind to in an Angular2 Template. How should I do this?

Update:

Here is the html:

<canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [colors]="colors" [options]="barChartOptions" [legend]="barChartLegend"
    [chartType]="barChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)">
</canvas>
2
  • Could you add the html? Commented Oct 21, 2016 at 13:23
  • @FabioAntunes Sure, please see the edit Commented Oct 21, 2016 at 13:25

1 Answer 1

1

In your html:

...[colors]="getColors()"

In your .ts file:

getColors() {
  return [{
     backgroundColor: this.barChartData.map(d => d > threshold ? red : green)
   }];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Really neat solution, but this only returns the background colour for the first bar...
I had to use backgroundColor: this.barChartData[0].data.map(d => d > this.target ? red : green)
Oh, and the > should be a <, but aside from that - a really nice solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.