Chartjs-Accessing data from the callback function of a bar chart using chart js

0👍

This should work:

...
options: {
  tooltips: {
    callbacks: {
      label: (context, data)  => data.datasets[context.datasetIndex].data[context.index].text
    }
  }
...

jsfiddle

0👍

You just need to update the version of chart.js you are using to the latest V2 version since V3 has breaking changes.

Also you need to specify the x for the number for a horizontalBar instead of a y in both the dataset and the tooltip callback:

var ctx = document.getElementById('chartJSContainer').getContext('2d');

new Chart(ctx, {
  type: 'horizontalBar',
  data: {
    labels: ['2017/06/12', '2017/06/23', '2017/07/12', '2017/07/23', '2017/08/12', '2017/08/23', '2017/09/12'],
    datasets: [{
      label: 'Values',
      data: [{
          x: 12,
          value: 12,
          text: "test1"
        },
        {
          x: 3,
          value: 13,
          text: "test2"
        },
        {
          x: 1,
          value: 15,
          text: "test3"
        },
        {
          x: -3,
          value: 5,
          text: "test4"
        },
        {
          x: 67,
          value: 18,
          text: "test5"
        },
        {
          x: 12,
          value: 11,
          text: "test6"
        },
        {
          x: 13,
          value: 19,
          text: "test7"
        }
      ],
      fill: false,
      borderWidth: 2
    }]
  },
  options: {
    tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
          var item = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
          return item.x + ' ' + item.value + item.text;
        }
      }
    },
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

Leave a comment