简体   繁体   中英

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 MP 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
                }
          }]
          }
        }
    });

you can add this in options.

legend: {
     display: true
}

Solved, the Bootstrap template I was using had this code somewhere in its .js

Chart.defaults.global.legend = {
  enabled: false
};

To show the legend label the chart, add this to your configuration.

legend: {
    display: true
}

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM