[Chartjs]-Custom tooltip title based on dictionary mapping of values

1👍

You can add an object with translations where the key is the value from the label and the value is the full country name:

var example2 = [229, 113, 109];
var labels2 = ["GER", "FRA", "LT"];
var translations = {
  GER: 'Germany',
  FRA: 'France',
  LT: "Italy"
}

var barChartData2 = {
  labels: labels2,
  datasets: [{
    label: 'Student Count',
    backgroundColor: '#ccece6',
    data: example2
  }]
};

function drawChart(el, data, title) {
  var ctx = document.getElementById(el).getContext("2d");
  var bar = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
      // Elements options apply to all of the options unless overridden in a dataset
      // In this case, we are setting the border of each bar to be 2px wide and green
      elements: {
        rectangle: {
          borderWidth: 2,
          borderColor: '#98c4f9',
          borderSkipped: 'bottom'
        }
      },
      responsive: true,
      legend: {
        position: 'bottom',
      },
      title: {
        display: true,
        text: title
      },
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: 0,
            min: 0
          }
        }],
        xAxes: [{
          ticks: {
            // Show all labels
            autoSkip: false,
            callback: function(tick) {
              var characterLimit = 20;
              if (tick.length >= characterLimit) {
                return tick.slice(0, tick.length).substring(0, characterLimit - 1).trim() + '...';;
              }
              return tick;
            }
          }
        }]
      },
      tooltips: {
        callbacks: {
          title: function(tooltipItem) {
            return translations[tooltipItem[0].xLabel];
          }
        }
      }
    }
  });
  console.log(bar);
};

drawChart('canvas0', barChartData2, 'example title');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.js"></script>

<div id="container">
  <canvas id="canvas0"></canvas>
</div>

Leave a comment