ChartJS with legend - Javascript Chart.js

Javascript examples for Chart.js:Legend

Description

ChartJS with legend

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>chart.js line 2.0</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.js"></script> 
   </head> 
   <body> 
      <canvas id="myChart" width="400" height="250"></canvas> 
      <script type="text/javascript">
var autoDisplayLegendPlugin = {/*from w  w  w .j  ava2s  .co m*/
  beforeUpdate: function(chartInstance) {
    if (chartInstance.options.autoDisplayLegend) {
      var dataset = chartInstance.data.datasets[0];
      if (dataset.label)
        chartInstance.options.legend.display = true;
      else
        chartInstance.options.legend.display = false;
    }
  }
};
Chart.pluginService.register(autoDisplayLegendPlugin);
var data = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    fill: false,
    lineTension: 0.1,
    backgroundColor: "rgba(75,192,192,0.4)",
    borderColor: "rgba(75,192,192,1)",
    borderCapStyle: 'butt',
    borderDash: [],
    borderDashOffset: 0.0,
    borderJoinStyle: 'miter',
    pointBorderColor: "rgba(75,192,192,1)",
    pointBackgroundColor: "#fff",
    pointBorderWidth: 1,
    pointHoverRadius: 5,
    pointHoverBackgroundColor: "rgba(75,192,192,1)",
    pointHoverBorderColor: "rgba(220,220,220,1)",
    pointHoverBorderWidth: 2,
    pointRadius: 5,
    pointHitRadius: 10,
    data: [],
  }]
};
var myLineChart = new Chart("myChart", {
  type: "line",
  data: data,
  options: {
    autoDisplayLegend: true
  }
});
setTimeout(function() {
  data.datasets[0].label = "The Label"
  data.datasets[0].data.push(10, 20)
  myLineChart.update()
}, 2000)

      </script>  
   </body>
</html>

Related Tutorials