I'm new in ChartJS and I have some problems with the legend. I have a simple bar chart with just 3 bars like:
<div class="x_panel">
<div class="x_title">
<h2>Bar graph</h2>
<ul class="nav navbar-right panel_toolbox" style="padding-left:5%">
<li>
<a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
</li>
<li>
<a class="close-link"><i class="fa fa-close"></i></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<canvas id="mybarChart"></canvas>
</div>
</div>
for which I'm trying to display the legend bellow the chart like in the attached image
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: '# of Votes',
backgroundColor: "#000080",
data: [80]
}, {
label: '# of Votes2',
backgroundColor: "#d3d3d3",
data: [90]
},
{
label: '# of Votes3',
backgroundColor: "#add8e6",
data: [45]
}]
},
options: {
legend: {
display: true,
labels: {
fontColor: "#000080",
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
But my displayed chart is empty :( I've also tried displaying the legend by adding another div bellow the canvas and calling it by:
document.getElementById('barlegend').innerHTML = mybarChart.generateLegend();
with the same result :(
What am I doing wrong?
To make this behave the same as standard Chart. js charts, the function onLegendClicked is invoked when a mouse click occurs on a legend label. This function toggles the hidden state of individual datasets and changes label text style between normal and strike-through.
Based on the code that you supplied in your question, it looks like you forgot to add labels
data in your chart data object. Without this information chartjs is not able to generate your axis and map each dataset data to it.
Also, since you mentioned you wanted the legend to be below the chart, I added the display: bottom
option. Here is the working code.
var ctx = document.getElementById("mybarChart").getContext("2d");
var mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Votes'],
datasets: [{
label: '# of Votes',
backgroundColor: "#000080",
data: [80]
}, {
label: '# of Votes2',
backgroundColor: "#d3d3d3",
data: [90]
}, {
label: '# of Votes3',
backgroundColor: "#add8e6",
data: [45]
}]
},
options: {
legend: {
display: true,
position: 'bottom',
labels: {
fontColor: "#000080",
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
Here is a working codepen example as well.
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