Chartjs-Tooltip on each data point in Chartjs

1👍

Inside titleTooltip in the pasted code, you replace sum with the last entry from MONTHS. The tooltip from the image however suggests that in the real code, you create an array with 77 and all entries from MONTHS, then you probably return 'Sum: ' + sum, which results in the string you can see in the tooltip.

In order to see all the months on a separate line, you could change your code as follows and return sum as an array:

const titleTooltip = ctx => {
  let sum = ['Sum: 77'];
  MONTHS.forEach(month => {
    sum.push(month);
  });    
  return sum;
}

The resulting tooltip still doesn’t make much sense but you’ll see all months on a different line. Therefore, you to extend the function titleTooltip in order to obtain the desired result.

Please take a loo at your amended code and see how it works.

function trendsChart(labels1, datasets1, chartId) {
  var MONTHS = ["January", "February", "March", "April", "May", "June"];
  var data = {
    labels: labels1,
    datasets: datasets1,
  };

  // Tooltip
  const titleTooltip = ctx => {
    let sum = ['Sum: 77'];
    MONTHS.forEach(month => {
      sum.push(month);
    });    
    return sum;
  }

  var randomScalingFactor = function() {
    return (Math.random() > 0.5 ? 1.0 : 1.0) * Math.round(Math.random() * 100);
  };

  var line1 = [randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor(), randomScalingFactor()];

  myChart = new Chart(chartId, {
    type: 'line',
    data: data,
    options: {
      maintainAspectRatio: false,
      responsive: true,
      scales: {
        x: {
          barPercentage: 1.6,
          gridLines: {
            drawBorder: false,
            color: 'rgba(225,78,202,0.1)',
            zeroLineColor: "transparent",
          },
          ticks: {
            padding: 0,
            fontColor: "#9a9a9a"
          },
          title: {
            display: true,
            text: 'Week Of'
          }
        },
        y: {
          barPercentage: 1.6,
          gridLines: {
            drawBorder: false,
            color: 'rgba(225,78,202,0.1)',
            zeroLineColor: "transparent",
          },
          ticks: {
            padding: 0,
            fontColor: "#9a9a9a"
          },
          stacked: false,
          title: {
            display: true,
            text: 'Count'
          }
        }
      },
      plugins: {
        tooltip: {
          //yAlign: 'bottom',
          callbacks: {
            title: titleTooltip,
            label: ctx => ctx.label + ': ' + ctx.parsed.y
          }
        }
      }
    }

  });

  return myChart;

}

trendsChart(['created', 'tested', 'reviewed', 'approved'], [{ data: [1, 5, 3, 2]}], 'myChart');
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
<canvas id="myChart"></canvas>

Leave a comment