Chartjs legend still not visible even after setting it to true
P粉595605759
P粉595605759 2023-09-14 18:38:17
0
1
576

I'm relatively new to ChartJS and I'm looking for a way to display labels on my donut chart. I tried setting the visibility of the legend to true in the options but still doesn't work.

var data = [{
        data: [successfulBuildsCount, failureBuildsCount],
        labels: ["成功", "失败"],
        backgroundColor: [
          "绿色",
          "红色"
        ],
        borderColor: "#fff"
      }];

      var options = {
        legend: { display: true, },
        title: {
          display: true,
        },

        plugins: {
          datalabels: {
            formatter: (value, ctx) => {

              let sum = 0;
              let dataArr = ctx.chart.data.datasets[0].data;
              dataArr.map(data => {
                sum += data;
              });
              let percentage = (value * 100 / sum).toFixed(2) + "%";
              return percentage;


            },
            color: '#fff',
          }
        }
      };


      var ctx = document.getElementById("chartContainer");
      var myChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
          datasets: data
        },
        options: options
      });
P粉595605759
P粉595605759

reply all(1)
P粉041758700

The legend should be displayed by default. If it doesn't show up, I'm assuming you're using treeshaking and haven't imported and registered the legend plugin like this:

import { Chart, Legend } from 'chart.js';

Chart.register(Legend);

Or you can make sure you don't miss anything by letting chart.js import and register everything:

import Chart from 'chart.js/auto';
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template