Chartjs-Chart.js multiTooltip Labels in Pie

1👍

You use the customTooltips option. Here is an example adapted from https://github.com/nnnick/Chart.js/blob/master/samples/pie-customTooltips.html

HTML

<canvas id="myChart" width="400" height="200"></canvas>
<div id="chartjs-tooltip"></div>

CSS

#chartjs-tooltip {
    opacity: 0;
    position: absolute;
    background: rgba(0, 0, 0, .7);
    color: white;
    padding: 3px;
    border-radius: 3px;
    -webkit-transition: all .1s ease;
    transition: all .1s ease;
    pointer-events: none;
    -webkit-transform: translate(-50%, 0);
    transform: translate(-50%, 0);
}
#chartjs-tooltip.above {
    -webkit-transform: translate(-50%, -100%);
    transform: translate(-50%, -100%);
}
#chartjs-tooltip.above:before {
    border: solid;
    border-color: #111 transparent;
    border-color: rgba(0, 0, 0, .8) transparent;
    border-width: 8px 8px 0 8px;
    bottom: 1em;
    content:"";
    display: block;
    left: 50%;
    top: 100%;
    position: absolute;
    z-index: 99;
    -webkit-transform: translate(-50%, 0);
    transform: translate(-50%, 0);
}

JS

var ctx = $("#myChart").get(0).getContext("2d");

var data = [{
    value: 300,
    color: "#F7464A",
    highlight: "#FF5A5E",
    label: "Red",
    otherData: "<div>Horror: 10%</div><div>Romance: 30%</div><div>Rest: 70%</div>"
}, {
    value: 50,
    color: "#46BFBD",
    highlight: "#5AD3D1",
    label: "Green",
    otherData: "<div>Horror: 25%</div><div>Romance: 25%</div><div>Rest: 50%</div>"
}, {
    value: 100,
    color: "#FDB45C",
    highlight: "#FFC870",
    label: "Yellow",
    otherData: "<div>Horror: 1%</div><div>Romance: 3%</div><div>Rest: 96%</div>"
}]


var tot = 0;
data.forEach(function (item) {
    tot += item.value;
})
tot *= 0.01;

var myPieChart = new Chart(ctx).Pie(data, {
    tooltipTemplate: "<%=label%>",
    customTooltips: function (tooltip) {
        // Tooltip Element
        var tooltipEl = $('#chartjs-tooltip');

        // Hide if no tooltip
        if (!tooltip) {
            tooltipEl.css({
                opacity: 0
            });
            return;
        }

        // Set caret Position
        tooltipEl.removeClass('above below');
        tooltipEl.addClass(tooltip.yAlign);

        // Set Text
        data.forEach(function(item) {
            if (item.label == tooltip.text)
                tooltipEl.html(item.otherData);
        })

        // Find Y Location on page
        var top = tooltip.y - tooltip.caretHeight - tooltip.caretPadding;

        // Display, position, and set styles for font
        tooltipEl.css({
            opacity: 1,
            left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
            top: tooltip.chart.canvas.offsetTop + top + 'px',
            fontFamily: tooltip.fontFamily,
            fontSize: tooltip.fontSize,
            fontStyle: tooltip.fontStyle,
        });
    }
});

Fiddle – http://jsfiddle.net/u463hctb/1/

Leave a comment