Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

358
Visualizações
ChartJS show value in legend (Chart.js V3.5)

I need the value of chart show after name of data for example ([colour of data] Car 50, [colour of data] Motorcycle 200). I've tried change the value of legend title but it doesn't work at all

Here is it my code

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,
                }
            });
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use a custom generateLabels function for this:

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],
            }))
          }
        }
      }
    }
  }
}

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

about 4 years ago · Juan Pablo Isaza Relatório

0

The below is a direct over ride of the default label generation found in the controller here. I have made one change on the text property within the generateLabels function in order to append the data value. It preserves the data toggling and strikethrough styling when a label is toggled.

    plugins: {
        legend: {
            labels: {
                generateLabels(chart) {
                    const data = chart.data;
                    if (data.labels.length && data.datasets.length) {
                        const {labels: {pointStyle}} = chart.legend.options;
    
                        return data.labels.map((label, i) => {
                            const meta = chart.getDatasetMeta(0);
                            const style = meta.controller.getStyle(i);
    
                            return {
                                text: `${label}: ${data['datasets'][0].data[i]}`,
                                fillStyle: style.backgroundColor,
                                strokeStyle: style.borderColor,
                                lineWidth: style.borderWidth,
                                pointStyle: pointStyle,
                                hidden: !chart.getDataVisibility(i),
    
                                // Extra data used for toggling the correct item
                                index: i
                            };
                        });
                    }
                    return [];
                }
            },
    
            onClick(e, legendItem, legend) {
                legend.chart.toggleDataVisibility(legendItem.index);
                legend.chart.update();
            }
        }
        //...
    }


  [1]: https://github.com/chartjs/Chart.js/blob/master/docs/samples/legend/html.md
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda