Toma
Toma

Reputation: 11

Chart.js - Styling Legend - ONE legend entry per line

I need that all legend entries would be always from new line:

new line

while now I have this situation:

this situation

I have been searching Vue Chart.js legend or legend label option to help me, but I can't find any. Maybe someone knows such an option?

my code:

export default {
extends : Pie,
computed: {....},
mounted() {

  this.renderChart({ .... }, {
    responsive         : true,
    maintainAspectRatio: false,

    legend             : {
      position: 'bottom',
      align: "start",

      labels:{
        boxWidth: 20,
        usePointStyle:true
        ???
      }
    }
  });
}

};

Upvotes: 1

Views: 2848

Answers (1)

Ezra Siton
Ezra Siton

Reputation: 7741

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>

Upvotes: 4

Related Questions