javascriptjquerycsschartschart.js2

Removing legend on charts with chart.js v2


I'm making a homepage using, Bootstrap, JQuery and Chart.js (v2). I had my implementation working using v1, but recently just got into Bower and downloaded v2 using that.

I'm making a grid of 4 columns each containing a pie chart, however the scaling in v2 is sort of confusing for me to get working. I want the charts to be responsive so they scale properly with the smaller devices such as tablets and smartphones, and one of my problems is getting rid of the legend of the charts as well as the hover information when hovering the mouse over the sections of my chart.

index.html

<body>
    <div class="container">
        <div class="row">
            <div class="col-xs-3">
                <canvas id="chart1"></canvas>
            </div>
            <div class="col-xs-3">
                <canvas id="chart1"></canvas>
            </div>
            <div class="col-xs-3">
                <canvas id="chart1"></canvas>
            </div>
            <div class="col-xs-3">
                <canvas id="chart1"></canvas>
            </div>
        </div>
    </div>
</body>

functions.js

$(document).ready(function(){
    var canvas = $("#chart1");
    var data = {
        labels: [],
        datasets: [{
            data: [10, 10],
            backgroundColor: ["#F7464A", "#FDB45C"],
            hoverBackgroundColor: ["#FF5A5E", "#FFC870"]
        }]
    };

    var chart1 = new Chart(canvas, {
        type: "pie",
        data: data,
    });
});

If I remove the empty "labels" field the chart doesn't work anymore. And by the looks of it there is a small spacing at the top of the chart which could indicate that the headers are written, but they are just empty strings.

Does anyone have an idea of how to remove the legend, and the hover description? I simply can't get my head around how this is used

I will get my hands around a jsfiddle as soon as I get time!

EDIT: Link to the docs: https://nnnick.github.io/Chart.js/docs-v2/#getting-started


Solution

  • From chart.js version 2.x backwards:

    The options object can be added to the chart when the new Chart object is created.

    var chart1 = new Chart(canvas, {
        type: "pie",
        data: data,
        options: {
             legend: {
                display: false
             },
             tooltips: {
                enabled: false
             }
        }
    });