Search code examples
javascriptchartschart.jsgraph-visualization

charts js, doughnut chart not rendering tooptips correctly


i have a multilevel donut chart but it is not rendering correctly here is code the problem is, onmouseover on all green parts it says objects, on all grey parts it says products, solution i would like is, on outer ring it should say products, in middle objects, and inner most should be materials, grey areas should just show number. here is a jsfiddle of the problem Code:

var op=93;
var ap=99;
var mp=66;
 var ctx = new Chart(myChart, {
        type: 'doughnut',

        data: {
            labels: ['Objects', 'Products', 'Materials'],
            datasets: [{
                label: 'Objects',
                data: [op, 100 - op],
                backgroundColor: ['#006a4e','#eeeeee'],
                hoverOffset: 4
            },{
                label: 'Products',
                data: [ap, 100 - ap],
                backgroundColor: ['#2e856e', '#eeeeee'],
                hoverOffset: 4
            },
                {
                    label: 'Materials',
                    data: [mp, 100 - mp],
                    backgroundColor: ['#5ca08e', '#eeeeee'],
                    hoverOffset: 4
                }
            ]
        },
        options: {
            //cutoutPercentage: 40,
            height: 200,
            width:200

        }
    });
 

Solution

  • You can achieve that fairly simple with Chart.JS 2.7.2. Add labels to each dataset like this:

    data: {
      labels: ['Existing', 'Non'],
      datasets: [
        {
          labels: ['Objects', 'Non-objects'],
          ...
        }, {
          labels: ['Products', 'Non-products'],
          ...
        },
        {
          labels: ['Materials', 'Non-materials'],
          ...
        }
      ]
    }
    

    And add the following label tooltip callback:

    tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
          var dataset = data.datasets[tooltipItem.datasetIndex];
          var index = tooltipItem.index;
          return dataset.labels[index] + ": " + dataset.data[index];
        }
      }
    }
    

    Demo: https://jsfiddle.net/adelriosantiago/fxd6vops/3/

    I am sure it is possible with Chart.JS > 3.0 too but I have no idea how since quite a few things changed in the structure.