DavideViolante / chartjs-plugin-labels

Plugin for Chart.js to display percentage, value or label in Pie or Doughnut.
MIT License
55 stars 18 forks source link

Not working for multiple datasets #9

Closed pellyadolfo closed 2 years ago

pellyadolfo commented 2 years ago

This was also reported here

https://github.com/emn178/chartjs-plugin-labels/issues/111

Example:

 const myChart = new Chart(document.getElementById('myChart'), {
  type: 'doughnut',
  data: {
      labels: ['Value1', 'Value2', 'Value3', 'Value4'],
      datasets: [{
          backgroundColor: ['#00FF00', '#0000FF'],
          data: [50, 50]
        }, {
          backgroundColor: ['#00FFFF', '#00FFFF'],
          data: [50, 50],
        }],
  },
  options: {
    plugins: {
          tooltip: {
                callbacks: {
                  label: function(context) {
                    const labelIndex = (context.datasetIndex * 2) + context.dataIndex;
                    return context.chart.data.labels[labelIndex] + ': ' + context.formattedValue + '%';
                  }
                },
          },
        labels: {
              render: 'image',
              images: [
                  null, 
                  null, 
                  {
                    src: 'http://simpleicon.com/wp-content/uploads/rocket.png',
                    width: 64,
                    height: 64
                  },
                  null
             ],
          },
    }
  }
});
pellyadolfo commented 2 years ago

ok fixed it by adding a index to my dataset items

  data: {
      labels: ['Value1', 'Value2', 'Value3', 'Value4', 'Value5', 'Value6'],
      datasets: [{
          backgroundColor: ['#FF0000', '#00FF00', '#0000FF'],
          data: [50, 40, 10],
          index: 0
        }, {
          backgroundColor: ['#00FFFF', '#00FFFF', '#00FFFF'],
          data: [50, 40, 10],
          index: 1
        }],
  },

and using this index to exclude unwanted items:

          render: function (arg) {
              if (arg.dataset.index == 0)
                  return {};
                     if (arg.index == 0) {
                     return { 
                    src: "put_your_image_here",
                    width: 50,
                    height: 50 
                  };
                      ......
            } 

              }

Thanks for your library