Home  >  Q&A  >  body text

Chartjs legend still not visible even after setting it to true

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粉595605759P粉595605759400 days ago518

reply all(1)I'll reply

  • P粉041758700

    P粉0417587002023-09-15 16:30:04

    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';
    

    reply
    0
  • Cancelreply