Chartjs-Bar chart legend adjustments – Chart JS

0👍

Unfortunately, there is no way to customize the default legend in the manner that you are wanting. Fortunately, however, chart.js thought of this and provided a mechanism for you to generate and style your own legend outside of the canvas object (using regular html/css).

You can use the legendCallback options property to define a method that generates your legend html and then call the chart .generateLegend() prototype method to place into your page. Here is what I mean.

HTML for my page.

<div style="width:25%;">
  <canvas id="mybarChart"></canvas>
  <div id="legend"></div>    
</div>

Then I define how the legend will look in the ‘legendCallback’ option property.

legendCallback: function(chart) {
  var text = [];
  text.push('<ul class="' + chart.id + '-legend">');
  for (var i = 0; i < chart.data.datasets.length; i++) {
    text.push('<li><div class="legendValue"><span style="background-color:' + chart.data.datasets[i].backgroundColor + '">&nbsp;&nbsp;&nbsp;&nbsp;</span>');

    if (chart.data.datasets[i].label) {
      text.push('<span class="label">' + chart.data.datasets[i].label + '</span>');
    }

    text.push('</div></li><div class="clear"></div>');
  }

  text.push('</ul>');

  return text.join('');
}

Finally, I add the legend html to my page.

$('#legend').prepend(mybarChart.generateLegend());

As always, here is a codepen example showing a working solution. You can change your legend look and feel simply by changing the html that is generated by the callback and using css.

Leave a comment