[Chartjs]-Chart.js Treemap Adding custom text to each rectangle

1👍

You can use the formatter options in the labels section:

const options = {
  type: 'treemap',
  data: {
    datasets: [{
      label: '# of Votes',
      tree: [12, 19, 3, 5, 2, 3],
      backgroundColor: 'pink',
      labels: {
        display: true,
        formatter(ctx) {
          const data = ctx.chart.data;
          return `Custom Text: ${data.datasets[ctx.datasetIndex].tree[ctx.dataIndex]}`;
        }
      },
    }]
  },
  options: {}
}

const 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.7.0/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-chart-treemap@2.0.1/dist/chartjs-chart-treemap.js"></script>
</body>

Leave a comment