2👍
✅
Used the legendCallback function to create a separate legend.
https://jsfiddle.net/ztnb3h7y/
HTML :
<div id="canvas-holder" style="width:100%">
<canvas id="myChart" width="400" height="400" />
</div>
<div id="chartjs-legend" style="width:100%;" >
</div>
CSS :
.Mylegend { list-style: none; }
.Mylegend li { float: left; margin-right: 10px; }
.Mylegend span
{ border: 1px solid #ccc; float: left; width: 15px; height: 12px; margin: 2px; }
JS :
function containsObject(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i].label == obj.label ) {
return true;
}
}
return false;
}
var ctx = $("#myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Market ", "J1", "J2","Market","J Share"],
datasets: [{
data: [61, 11,27],
backgroundColor: [
'#00205A',
'#97BAFF',
'#D9D9D9',
'#00205A',
'#747474',
],
labels: [
'Market Share',
'J1',
'J2'
]
}, {
data: [61, 39],
backgroundColor: [
'#00205A',
'#747474',
],
labels: [
'Market Share',
'J Share',
],
}, ]
},
options: {
responsive: true,
showAllTooltips: true,
legendCallback: function(chart) {
var text = [];
var legs = [];
for( var j=0; j<chart.data.datasets.length;j++)
{
for (var i = 0; i < chart.data.datasets[j].data.length; i++)
{
var newd = { label: chart.data.datasets[j].labels[i] , color: chart.data.datasets[j].backgroundColor[i] };
if( !containsObject (newd,legs) )
{
legs.push(newd);
}
}
}
text.push('<ul class="Mylegend ' + chart.id + '-legend">');
for( var k =0;k<legs.length;k++)
{
text.push('<li><span style="background-color:' + legs[k].color + '"></span>');
text.push(legs[k].label);
text.push('</li>');
}
text.push('</ul>');
return text.join("");
},
legend: {
display: false,
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ': ' + dataset.data[index];
}
}
}
}
});
$("#chartjs-legend").html(myChart.generateLegend());
Source:stackexchange.com