Chartjs-How to show different tooltips on charts (in columns)?

0👍

You have to change your tooltip mode from label to point and dont hard code the datasetIndex. To solve deprecation issue, remove the barpercentage from the scale option and specify it in every dataset or you can configure it globally before you make the chart like this: Chart.defaults.global.datasets.bar.barPercentage = 0.5;.

var barChart = {
  labels: ["2016", "2017", "2018", "2019", "2020"],
  datasets: [{
      label: '',
      backgroundColor: "rgba(34,42,171, 0.7)",
      borderColor: 'rgba(34,42,171, 1)',
      borderWidth: 1,
      barPercentage: 0.5,
      data: [220, 315, 380, 470, 520]
    },
    {
      label: '',
      backgroundColor: "#ceb947",
      barPercentage: 0.5,
      data: [135, 190, 180, 160, 240]
    },
  ]
};
var ctx4 = document.getElementById("chartJSContainer").getContext("2d");
window.newBar = new Chart(ctx4, {
  type: 'bar',
  data: barChart,
  options: {
    title: {
      display: false,
      fontStyle: 'bold',
      text: "Figure"
    },
    legend: {
      display: false,
      position: "bottom",
      padding: 20,
      labels: {}
    },
    tooltips: {
      mode: 'point',
      bodySpacing: 10,
      cornerRadius: 0,
      titleFontSize: 16,
      bodyFontSize: 14,
      titleMarginBottom: 15,
      callbacks: {
        label: function(tooltipItem, data) {
          var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
          value = value.toString();
          value = value.split((/(?=(?:..)?$)/));
          value = value.join(',');
          return 'Total: ' + value + ' %';
        }
      }
    },

    scales: {
      xAxes: [{
        gridLines: false,
        ticks: {
          fontColor: 'rgb(37,39,103)',
          fontSize: '14',
          autoSkip: false,
          maxRotation: 45,
          minRotation: 45,
          padding: 15
        }
      }],
      yAxes: [{
        ticks: {
          fontColor: 'rgb(37,39,103)',
          fontSize: '14',
          beginAtZero: true,
          stepSize: 100,
          userCallback: function(value, index, values) {
            value = value.toString();
            value = value.split(/(?=(?:..)?$)/);
            value = value.join(',');
            return value + ' %';
          }
        }
      }]
    },
    responsive: true,
  }
});
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
</body>

Leave a comment