Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js not showing legends

Chart.js isn't showing legends. I'm using version 2.4.0, and I've included the Chart.bundle.min.js script in my website.

All of the variables like lineaRoja, puntos, MuPu were defined and the data is shown correctly.

The problem is the legends with Falla balanceada, Mu y Pu aplicados and Diagrama M-P with their respective colours aren't showing. Only the tooltips when I hover on the dots show.

var canvas = document.getElementById(domId);
var ctx = canvas.getContext("2d");
var lineChart = new Chart(ctx, {
        type: 'line',
        data: {
            datasets: [{
                label: 'Diagrama M-P',
                data: puntos
            }, {
                label: 'Falla balanceada',
                backgroundColor: 'rgba(0,0,0,0)',
                borderColor: 'rgba(130,0,0,0.6)',
                data: [{ x: 0, y: 0}, { x: lineaRoja[0], y: lineaRoja[1] }],
                borderDash: [10, 5]
            }, {
                type: 'scatter',
                data: MuPu,
                fill: false,
                showLine: false,
                backgroundColor: 'rgba(0,130,0,0.6)',
                label: 'Mu y Pu aplicados',
                pointRadius: 6

            }]
        },
        options: {
          animation: { duration: 0 },

            scales: {
              xAxes: [{
                  type: 'linear',
                  position: 'bottom',
                  scaleLabel: {
                    display: true,
                    labelString: 'Ton'
                  }
              }],
              yAxes: [{
                scaleLabel: {
                  display: true,
                  labelString: 'Ton m'
                },
                ticks: {
                    min: 0,
                    beginAtZero: true
                }
          }]
          }
        }
    });
like image 614
Chris Vilches Avatar asked Mar 08 '23 20:03

Chris Vilches


1 Answers

Next to adding the legend config into options Legend - Chart.js docs :

const chart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        plugins: {
            legend: {
                display: true,
            }
        }
    }
});

You have to import and register the module when using build tools like Webpack or Rollup Integration - Chart.js docs:

Chart.register(
  Legend,
)

Or use one of the auto-register methods :

import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);

or:

import Chart from 'chart.js/auto';
like image 133
tdhulster Avatar answered Mar 16 '23 05:03

tdhulster