ChartJS 在图例中显示值 (Chart.js V3.5)

Ray*_*der 5 javascript laravel chart.js

我需要在数据名称后显示图表的值,例如([数据颜色] 汽车 50,[数据颜色] 摩托车 200)。我尝试过更改图例标题的值,但它根本不起作用

这是我的代码:

var ctx = document.getElementById('top-five').getContext('2d');
var myChartpie = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: {!! $top->pluck('name') !!},
    datasets: [{
      label: 'Statistics',
      data: {!! $top->pluck('m_count') !!},
      backgroundColor: {!! $top->pluck('colour') !!},
      borderColor: {!! $top->pluck('colour') !!},
    }]
  },
  options: {
    plugins: {
      legend: {
        display: true,
        title: {
          text: function(context) {//I've tried to override this but doesn't work
            var value = context.dataset.data[context.dataIndex];
            var label = context.label[context.dataIndex];
            return label + ' ' + value;
          },
        }
      },
    },
    responsive: true,
  }
});
Run Code Online (Sandbox Code Playgroud)

Lee*_*lee 9

generateLabels您可以为此使用自定义函数:

var options = {
  type: 'doughnut',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    }]
  },
  options: {
    plugins: {
      legend: {
        labels: {
          generateLabels: (chart) => {
            const datasets = chart.data.datasets;
            return datasets[0].data.map((data, i) => ({
              text: `${chart.data.labels[i]} ${data}`,
              fillStyle: datasets[0].backgroundColor[i],
              index: i
            }))
          }
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)