Chart JS legend label color is not getting changed to my desired/provided color while using generateLabel callback fn

49 Views Asked by At

Image to refer, Legend text color is black

While using generateLabel() for some use case, but inn that case the legend text color are coming as black, I want to know if there's a way to get that done as well. As we know we can do many things with the help of generateLabel().

The config I'm using:

{
        type: 'doughnut',
        plugins: [ChartDataLabels],
        data: {
          labels: ['Historical', 'Dead Stock'],
          datasets: [
            <any>{
              backgroundColor: ['#d927d6', '#437cb5'],
              data: [65, 35],
              color: 'white',
              pointStyle: 'rect',
              datalabels: {
                anchor: 'center',
                color: 'white',
                font: {
                  size: 25,
                  weight: 'bold',
                },
              },
            },
          ],
        },
        options: {
          plugins: {
            tooltip: { enabled: true },
            legend: {
              display: true,
              labels: {
                padding: 40,
                font: { size: 24 },
                color: '#FFFFFF',
                usePointStyle: true,
                generateLabels: <any>function (chart: any) {
                  const labels = chart.data.labels;
                  const datasets = chart.data.datasets;
                  const visibility: any = [];
                  chart.options.plugins.legend.labels.color = 'white';

                  for (let i = 0; i < datasets.length; i++) {
                    if (chart.isDatasetVisible(0) === false) {
                      visibility.push(true);
                    } else {
                      visibility.push(false);
                    }
                  }

                  return labels.map(function (label, index) {
                    const dataset = datasets[0];
                    const backgroundColor = dataset.backgroundColor[index];
                    const pointStyle = dataset.pointStyle;

                    // Customizing legend item appearance
                    return {
                      text: label,
                      fillStyle: backgroundColor,
                      strokeStyle: backgroundColor,
                      pointStyle: pointStyle,
                      index: index,
                      hidden: visibility[index],
                    };
                  });
                },
              },
              position: 'right',
            },
          },
        },
      }

NOTE: I tried this way because I need same pointStyle in legend, which was not working if I tried mentioning pointStyle: 'rect' inside dataset object and inside options -> plugins -> legend -> labels -> usePointStyle: true. But this didn't worked.

0

There are 0 best solutions below