Home > database >  Change font colour of data labels on bar chart - chartsjs-plugin-data-labels
Change font colour of data labels on bar chart - chartsjs-plugin-data-labels

Time:11-18

I have the following bar chart. here is the javascript options for it:

  public chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    legend: {
      display: true,
      labels: {
        fontColor: "black",
        fontSize: 12,
      },
    },
    scales: {
      yAxes: [
        {
          display: true,
          stacked: false,
          scaleLabel: {
            display: true,
            labelString: "Number of Students",
          },
          ticks: {
            stepSize: 5,
            min: 0,
            max: 30,
            fontSize: 12,
            fontColor: "black",
          },
        },
      ],
      xAxes: [
        {
          display: true,
          stacked: false,
          ticks: {
            fontSize: 12,
            fontColor: "black",
            precision: 0,
          },
        },
      ],
    },
  };

Here is the html:

          <canvas
            baseChart
            [datasets]="chartData"
            [labels]="chartLabels"
            [options]="chartOptions"
            [colors]="chartColors"
            [plugins]="[]"
            [legend]="true"
            [chartType]="'bar'"
            height="300px"
          >
          </canvas>

Sometimes the data labels appear on the bars (see picture), but i can't figure out how to change the colour to make them white. Does anyone know?

chart image

UPDATE:

Here is the chart with new chartOptions, but still doesn't change the colour of the data labels:

  chartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    legend: {
      display: true,
    },
    scales: {
      yAxes: [
        {
          display: true,
          stacked: false,
          scaleLabel: {
            display: true,
            labelString: "Number of Students",
          },
          ticks: {
            stepSize: 5,
            min: 0,
            max: 30,
            fontSize: 12,
            fontColor: "black",
          },
        },
      ],
      xAxes: [
        {
          display: true,
          stacked: false,
          ticks: {
            fontSize: 12,
            fontColor: "black",
            precision: 0,
          },
        },
      ],
    },
    plugins: {
      labels: {
        fontColor: "white",
        fontSize: 12,
      },
    },
  };

CodePudding user response:

I think the issue is because you add the baels plugin config inside the legend configuration.

It should be:

  options: {
  ...
    plugins: {
      labels: {
        fontColor: "black",
        fontSize: 12,
      },
    }
  ...
  }

CodePudding user response:

The problem was due to the 'chartsjs-plugin-data-labels' plugin i had. Fixed it by adding this to the datasets array.

        dataLabels: {
          colors: ["white"],
        },
  • Related