Shaun O
Shaun O

Reputation: 53

ChartJS 3.8.0 Stacked Bar Combined Labels

with chart.js 3.8.0, is it possible to consolidate labels on a stacked bar chart? The closest solution I've found is to add for tooltip footer callback and add extra text in the tooltip manually, but it does not include the legend/color icon associated with that dataset.

Example HTML:

<html>
<head></head>
<body>
<h1>
Stacked Bar Chart (chart.js)
</h1>
  <canvas id="chart_display"></canvas>
</body>
</html>

Example Javascript:

const data = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
  datasets: [
    {
    label: 'Retained',
    data: [62,68,74,80,66,84],
    backgroundColor: 'rgb(0, 178, 169)',
    order: 3,
    stack: 'stack1'
    },
    {
      label: 'Expired',
      data: [5,3,7,9,2,4],
      backgroundColor: 'rgb(207, 16, 45)',
      order: 3,
      stack: 'stack1'
    }
  ]
}

const config = {
    type: 'bar',
  data: data,
  options: {
    scales: {
        x: {
        stacked: true
      },
      y: {
        stacked: true
      }
    }
  },
};

const reportOutput = new Chart(
    document.getElementById('chart_display'),
  config
);

Example in JSFiddle

It appears to be possible in older versions as seen here: https://www.chartjs.org/docs/3.5.0/samples/bar/stacked.html

Hopefully, I've just overlooked a simple configuration option.

Upvotes: 2

Views: 3677

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31341

You need to add mode: 'index' to the tooltip configuration to achieve that behaviour:

const data = {
  labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
  datasets: [{
      label: 'Retained',
      data: [62, 68, 74, 80, 66, 84],
      backgroundColor: 'rgb(0, 178, 169)',
      order: 3,
      stack: 'stack1'
    },
    {
      label: 'Expired',
      data: [5, 3, 7, 9, 2, 4],
      backgroundColor: 'rgb(207, 16, 45)',
      order: 3,
      stack: 'stack1'
    }
  ]
}

const config = {
  type: 'bar',
  data: data,
  options: {
    plugins: {
      tooltip: {
        mode: 'index'
      }
    },
    scales: {
      x: {
        stacked: true
      },
      y: {
        stacked: true
      }
    }
  },
};

const reportOutput = new Chart(
  document.getElementById('chart_display'),
  config
);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<html>

<head></head>

<body>
  <h1>
    Stacked Bar Chart (chart.js)
  </h1>
  <canvas id="chart_display"></canvas>
</body>

</html>

Upvotes: 4

Related Questions