[Chartjs]-Chart JS Legend Styling

4👍

Here is the fixture. The legends are actually creating the colors but as its a custom legend you have to write a little css for workaround.

.legend ul li{list-style:none;}
.legend ul li span{ width:50px; height:15px;display:inline-block; margin-right:5px; }

Below is the working code:

// Dummy Data
    var data = {
        labels: [
            "Fuel Consumption (Miles)",
            "Distance Travelled (Miles)",
            "Distance Remaining (Miles)",
            "Fuel Cost (Pounds)",
            "Time Driving (Minutes)"
        ],
        datasets: [
            {
                data: [300, 50, 100, 25, 120],
                backgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56",
                    "#F86301",
                    "#FFFFFF"
                ],
                hoverBackgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56",
                    "#F86301",
                    "#FFFFFF"
                ]
            }]
    };

    var options = 

{
    segmentShowStroke: false,
    animateRotate: true,
    animateScale: false,
    percentageInnerCutout: 50,
    tooltipTemplate: "<%= value %>%",
    responsive: false,
    legend: {
        display:false
    }
}

// Today's Chart
var today = document.getElementById("today").getContext("2d");
var myDoughnutChart = new Chart(today, {
    type: 'doughnut',
    data: data,
    options: options
});

document.getElementById('legend').innerHTML = myDoughnutChart.generateLegend();
.legend {
   width: 50%;
   position: absolute;
   top: 100px;
   right: 20px;
   color: @light;
   font-family: @family;
   font-variant: small-caps;
   font-size: @size + 2;
}
.legend ul li{list-style:none;}
.legend ul li span{ width:50px; height:15px;display:inline-block; margin-right:5px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.js"></script>
<canvas id="today" style="width: 40%;"></canvas>
<div id="legend" class="legend"></div>

Leave a comment