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

1๐Ÿ‘

โœ…

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.

0๐Ÿ‘

HTML:

<canvas baseChart width="400" height="360"
        [data]="chartData"
        [options]="chartOptions"
        [type]="chartType">
</canvas>

TS:


import { Component, ViewChild, OnInit } from '@angular/core';
import { ChartConfiguration, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';

export class MyChartComponent implements OnInit {

  @ViewChild(BaseChartDirective) chart?: BaseChartDirective;

  constructor() {}

  ngOnInit(): void {}

  public chartData: ChartConfiguration['data'] = {
    datasets: [
      {
        data: [10, 32, 21, 48],
        label: 'My Data',
        backgroundColor: 'rgba(54, 162, 235, 0.2)',
        borderColor: 'rgba(54, 162, 235, 1)',
        pointBackgroundColor: 'rgba(54, 162, 235, 1)',
        pointBorderColor: 'rgba(255, 255, 255, 1)',
        pointHoverBackgroundColor: 'rgba(255, 255, 255, 1)',
        pointHoverBorderColor: 'rgba(54, 162, 235, 1)',
        fill: 'origin',
      },
    ],
    labels: ['A', 'B', 'C', 'D']
  };

  public chartOptions: ChartConfiguration['options'] = {
    elements: {
      line: {
        tension: 0.5
      }
    },
    scales: {
      x: {},
      y: {
        position: 'left',
        beginAtZero: true,
        grid: {
          color: 'rgba(100, 100, 100, 0.3)',
        },
        ticks: {
          color: '#666'
        }
      },
    },
    maintainAspectRatio: false,
    plugins: {
      legend: { display: true },
    }
  };

  public chartType: ChartType = 'line';
}

You only have to change these sample colors to your own ones.

Leave a comment