TinyTiger
TinyTiger

Reputation: 2111

Charts.js - How to set custom tooltip text for each dataset

Using charts.js, how do I add custom tooltip text for each dataset?

For dataset 1, I want to add "some text 1" to the tooltip.

For dataset 2, I want to add "some text 2" to the tooltip.

Using tooltip callbacks I can add extra text to the tooltip, but it applies the same text to the tooltips of both datasets. My code below is using a callback to do that. But how can I change the tooltip text for each dataset?

var chart = new Chart(ctx, {
  // The type of chart we want to create
  type: "line",
  // The data for our dataset
  data: {
    labels: monthLabels,
    datasets: [{
      label: "Dataset 1",
      data: [12, 123, 234, 32, 23],
    }, {
      label: "Dataset 2",
      data: [4, 54, 765, 45, 5],
    }]
  },
  // Configuration options go here
  options: {
    tooltips: {
      enabled: true,
      mode: 'single',
      callbacks: {
        label: function(tooltipItems, data) {
          return tooltipItems.yLabel + 'some text here';
        }
      }
    }
  }
});

Upvotes: 3

Views: 6400

Answers (1)

palaѕн
palaѕн

Reputation: 73966

You can do this easily by referring to the current dataset index tooltipItems.datasetIndex and then based on that index set the tooltip text like:

label: function(tooltipItems, data) {
    var text = tooltipItems.datasetIndex === 0 ? 'some text 1' : 'some text 2'
    return tooltipItems.yLabel + ' ' + text;
}

Working Demo:

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
  // The type of chart we want to create
  type: "line",
  // The data for our dataset
  data: {
    labels: Array.from({length: 5}, (x,i)=> `Label ${i+1}`),
    datasets: [{
      label: "Dataset 1",
      data: [12, 123, 234, 32, 23],
    }, {
      label: "Dataset 2",
      data: [4, 54, 765, 45, 5],
    }]
  },
  // Configuration options go here
  options: {
    tooltips: {
      enabled: true,
      mode: 'single',
      callbacks: {
        label: function(tooltipItems, data) {
          var text = tooltipItems.datasetIndex === 0 ? 'some text 1' : 'some text 2'
          return tooltipItems.yLabel + ' ' + text;
        }
      }
    }
  }
});
.chart-container {
   width: 500px;
}
#myChart {
  display: block; 
  width: 500px; 
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

<div class="chart-container">
    <canvas id="myChart"></canvas>
</div>

Upvotes: 4

Related Questions