[Chartjs]-Chart.js – Styling Legend – ONE legend entry per line

4πŸ‘

No way (Yet – true to April 20) to solve this by the API. You should generate custom HTML legends.
https://www.chartjs.org/docs/latest/configuration/legend.html#html-legends

The idea – you generate (by for loop) any HTML markup you want – and generate this inside the DOM (Not as part of chart.js canvas).

** Keep in mind generateLegend() legends not clickable by default.

β€œHello world” example:

var data = {
  labels: [
    "Red",
    "Blue",
    "orange"
  ],
  datasets: [{
    data: [300, 50, 100],
    backgroundColor: [
      "red",
      "blue",
      "orange"
    ],
    borderWidth: 1
  }]
};

var options = {
  legend: false,
  legendCallback: function(chart) {
    var elem = [];
    elem.push('<ul class="custom-legends">');
    for (var i = 0; i < chart.data.datasets[0].data.length; i++) {
      elem.push('<li><span class="dot" style="background-color:' + chart.data.datasets[0].backgroundColor[i] + '"></span>');
      if (chart.data.labels[i]) {
        elem.push(chart.data.labels[i]);
      }
      elem.push('</li>');
    }
    elem.push('</ul>');
    return elem.join("");
  },
}
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'doughnut',
  data: data,
  options: options
});



var legentElement = document.getElementById("legend");
/* insert custom HTML inside custom div */
legentElement.innerHTML = myChart.generateLegend();
ul.custom-legends{
  border: 1px solid black;
  list-style-type: none;
  padding-left: 0px;

}

ul.custom-legends li{
  border: 1px solid lightgray;
  list-style-type: none;
  padding: 5px;
  display: flex;
  align-items: center;
  justify-content: left;
}

.dot{
  border-radius: 50px;
  height: 10px;
  width: 10px;
  margin-right: 10px;
}
<div id="legend"></div>
<canvas id="myChart"></canvas>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>

Leave a comment