[Chartjs]-ChartJs shows the wrong labels

1👍

The error you had was that your tooltip config was wrong, in v3 the naming was changed from tooltips to tooltip if you change that it works fine:

const data = {
  labels: ['Summe', 'Noch um Ziel zu erreichen', 'Tage', 'Verbleibende Tage im Monat'],
  datasets: [{
      backgroundColor: ['#5ce1e6', '#2acaea'],
      data: [200, (800 - 200)]
    },
    {
      backgroundColor: ['#cd1076', '#8b0a50'],
      data: [4, (23 - 4)]
    },

  ]
};

var ctx = document.getElementById('chartJSContainer').getContext('2d');

// Configuration of the pie chart
let outterChart = new Chart(ctx, {
  type: 'pie',
  data: data,
  options: {
    responsive: true,
    plugins: {
      legend: {
        labels: {
          generateLabels: function(chart) {
            // Get the default label list
            const original = Chart.overrides.pie.plugins.legend.labels.generateLabels;
            const labelsOriginal = original.call(this, chart);

            // Build an array of colors used in the datasets of the chart
            var datasetColors = chart.data.datasets.map(function(e) {
              return e.backgroundColor;
            });
            datasetColors = datasetColors.flat();

            // Modify the color and hide state of each label
            labelsOriginal.forEach(label => {

              // Change the color to match the dataset
              label.fillStyle = datasetColors[label.index];
            });

            return labelsOriginal;
          }
        },
        onClick: function(mouseEvent, legendItem, legend) {
          // toggle the visibility of the dataset from what it currently is
          legend.chart.getDatasetMeta(
            legendItem.datasetIndex
          ).hidden = legend.chart.isDatasetVisible(legendItem.datasetIndex);
          legend.chart.update();
        }
      },
      tooltip: {
        callbacks: {
          label: function(context) {
            const labelIndex = (context.datasetIndex * 2) + context.dataIndex;
            return context.chart.data.labels[labelIndex] + ': ' + context.formattedValue;
          }
        }
      },
    }
  },
});
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>

Leave a comment