Chartjs-Chart.js (Customising tool tips of a stacked bar to represent each stacked data)

0👍

You could use label and footer tooltip callbacks and return a string array from each of them as shown below:

options: {
  tooltips: {
    callbacks: {       
      label: (tooltipItem, data) => data.datasets.map(ds => ds.label + ": " + ds.data[tooltipItem.index] + "%"),
      footer: tooltipItem => [
          "Avg: " + avgDATA[tooltipItem[0].index],
          "Sum: " + sumDATA[tooltipItem[0].index]              
        ]
    }
  },
  ...

Please take a look at your amended code and see how it works:

var dataBars = {
  labels: ["Day 1", "Day 2", "Day 3", "Day 4", "Day 5"],
  datasets: [{
      label: "Morning hours",
      fill: true,
      backgroundColor: "#dedede",
      data: [9, 11, 14, 17, 19]
    },
    {
      label: "Evening hours",
      fill: true,
      backgroundColor: "#dddddd",
      data: [12, 13, 18, 15, 20]
    },
    {
      label: "Night hours",
      fill: true,
      backgroundColor: "#f8f8f8",
      data: [9, 11, 14, 17, 19]
    }
  ]
};

var dataJason = {
  "meth": [
    { "avg": 3, "sum": 33 },
    { "avg": 34, "sum": 76 },
    { "avg": 73, "sum": 56 },
    { "avg": 9, "sum": 43 },
    { "avg": 11, "sum": 12 }
  ]
};

var avgDATA = [];
var sumDATA = [];

function techData() {
  var jdata = dataJason.meth;
  var jl = jdata.length;
  for (var i = 0; i < jl; i++) {
    avgDATA.push(dataJason.meth[i].avg);
    sumDATA.push(dataJason.meth[i].sum);
  }
}

function init() {
  techData();
  var bar = document.getElementById("bar").getContext('2d');
  var barChar = new Chart(bar, {
    type: 'bar',
    data: dataBars,
    options: {
      tooltips: {
        callbacks: {       
          label: (tooltipItem, data) => data.datasets.map(ds => ds.label + ": " + ds.data[tooltipItem.index] + "%"),
          footer: tooltipItem => [
              "Avg: " + avgDATA[tooltipItem[0].index],
              "Sum: " + sumDATA[tooltipItem[0].index]              
            ]
        }
      },
      scales: {
        xAxes: [{
          stacked: true
        }],
        yAxes: [{
          stacked: true
        }]
      }
    }
  });
}

init();
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<canvas id="bar" height="120"></canvas>

Leave a comment