Chartjs-How to change label color of ng2 chart in angular

0👍

We can change the font color of labels as shown below.

    public barChartOptions:any = {
scaleShowVerticalLines: false,
responsive: true,
legend: {
  display: true,
  labels: {
    fontColor: 'green'
  }
 }
 }

0👍

It took me a while to figure out how to achieve this theme change driven label color change properly. setColorschemesOptions of class import { ThemeService } from 'ng2-charts'; can be used.
Here’s my solution:
Let’s say your chart options looks like this

public chartOptions: ChartOptions = {
    maintainAspectRatio: true,
    responsive: true,
    legend: {
      position: 'bottom',
      labels: {
        fontColor: 'black'
      },
    },
    plugins: {
      datalabels: {
        formatter: (value, ctx) => {
          console.log(value, ctx);
          const label = ctx.chart.data.labels[ctx.dataIndex];
          return label;
        },
      },
      
    }
  };

Now you have to subscribe to the themeChange variable in ngOnInit() and use themeService to set the new value of this.chartOptions.legend.labels.fontColor every time a dark theme is selected, which can be done like:

import { Label, SingleDataSet, ThemeService } from 'ng2-charts';

constructor(
    private themeService: ThemeService
  ) { }

ngOnInit(): void {
    this.matService.themeSubject.subscribe((e) => {
      if(e === "purple-green" || e === "pink-bluegrey") {
        this.chartOptions.legend.labels.fontColor = "white";
        this.themeService.setColorschemesOptions(this.chartOptions);
      } else {
        this.chartOptions.legend.labels.fontColor = "black";
        this.themeService.setColorschemesOptions(this.chartOptions);
      }
    });
}

Leave a comment