Chartjs-Ng2-charts doughnut chart with different data per series

1๐Ÿ‘

โœ…

I finally got it to work with version 2.X. I basically flattened the heirarchical data structure and padded the multiple dataset arrays with zeros. Below is the code that will give you two layer doughnut chart with the second layer showing the split of the first layer section.

public summaryTreeChartLabels: Label[] = ['asdf', 'sdgf', 'dfhg', 'asdf_1', 'asdf_2', 'sdgf_1', 'sdgf_2', 'dfgh_1', 'dfgh_2'];

public summaryTreeChartData = [[34, 50, 26, 0,0,0,0,0,0], [0,0,0, 14, 20, 30, 20, 10, 16]];

public summaryTreeChartType: ChartType = 'doughnut';

enter image description here

1๐Ÿ‘

You can use object notation for this together with a custom tooltip label callback:

var options = {
  type: 'doughnut',
  data: {
    datasets: [{
        label: '# of Votes',
        data: [{
          id: 'parent1',
          key: 55
        }, {
          id: 'parent2',
          key: 55
        }, {
          id: 'parent3',
          key: 30
        }],
        borderWidth: 1,
      },
      {
        label: '# of Points',
        data: [{
          id: 'child1',
          key: 55
        }, {
          id: 'child2',
          key: 55
        }, {
          id: 'child3',
          key: 30
        }, {
          id: 'child4',
          key: 55
        }, {
          id: 'child5',
          key: 55
        }, {
          id: 'child6',
          key: 30
        }],
        borderWidth: 1
      }
    ]
  },
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          label: (ttItem) => (`${ttItem.raw.id}: ${ttItem.raw.key}`)
        }
      }
    },
    parsing: {
      key: 'key'
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>

Leave a comment