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 });
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:
Or you can make sure you don't miss anything by letting chart.js import and register everything: