我对ChartJS相对较新,我正在寻找一种在我的环形图上显示标签的方法。我尝试在选项中将图例的可见性设置为true,但仍然不起作用。
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粉0417587002023-09-15 16:30:04
默认情况下应该显示图例。如果没有显示,我假设您正在使用treeshaking,并且没有像这样导入和注册图例插件:
import { Chart, Legend } from 'chart.js'; Chart.register(Legend);
或者您可以通过让chart.js导入和注册所有内容来确保您没有遗漏任何内容:
import Chart from 'chart.js/auto';