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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With