Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add label for ChartJs Legend

In the ChartJs, how to add text/label above the legend. I don't want the label for the chart, but I need to place it above the legend.

I am using ChartJs for generating charts.

enter image description here

like image 665
Vamsi Avatar asked Aug 06 '18 06:08

Vamsi


1 Answers

You can use html to create your custom legend. Here is an example of how to creating a custom legend with custom title(and custom user interface).

function legendClickCallback(event) {
  event = event || window.event;

  var target = event.target || event.srcElement;
  while (target.nodeName !== 'LI') {
      target = target.parentElement;
  }
  var parent = target.parentElement;
  var chartId = parseInt(parent.classList[0].split("-")[0], 10);
  var chart = Chart.instances[chartId];
  var index = Array.prototype.slice.call(parent.children).indexOf(target);
  var meta = chart.getDatasetMeta(index);

  if (meta.hidden === null) {
    meta.hidden = !chart.data.datasets[index].hidden;
    target.classList.add('hidden');
  } else {
    target.classList.remove('hidden');
    meta.hidden = null;
  }
  chart.update();
}

var ctx = document.getElementById("myChart");
var myLegendContainer = document.getElementById("myChartLegend");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["values #1", "values #2"],
    datasets: [
      {
        label: "One",
        backgroundColor: "red",
        data: [26,36]
      },
      {
        label: "Two",
        backgroundColor: "blue",
        data: [34, 40]
      }

    ]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    }
  }
});

myLegendContainer.innerHTML = myChart.generateLegend();
var legendItems = myLegendContainer.getElementsByTagName('li');
for (var i = 0; i < legendItems.length; i += 1) {
  legendItems[i].addEventListener("click", legendClickCallback, false);
}
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
[class="0-legend"] {
  cursor: pointer;
  list-style: none;
  padding-left: 0;
}
[class="0-legend"] li {
  display: inline-block;
  padding: 0 5px;
}
[class="0-legend"] li.hidden {
  text-decoration: line-through;
}
[class="0-legend"] li span {
  border-radius: 5px;
  display: inline-block;
  height: 10px;
  margin-right: 10px;
  width: 10px;
}
.legend-box{
  border-color: gray;
  border-style: dashed;
  margin-top: 25px;
}
<script src="https://npmcdn.com/chart.js@latest/dist/Chart.bundle.min.js"></script>


<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"></canvas>
      <div class='legend-box'>
        <span>Chart legend</span>
        <div id="myChartLegend"></div>        
      </div>
    </div>
  </body>
</html>

I used the code of this example to create above example

like image 73
pouyan Avatar answered Oct 26 '22 22:10

pouyan