1

I have created a Multiple line Line chart using the ChartJS library on Laravel. It has two line. I want to add percentage data to my Line Chart Tooltips for each xLabel. But I am not able to use it in this wrapper. Could you help me out?

Example: Line: data (percent_data)%

Below code is giving only the first element on my Charts Tooltips

var ctx = document.getElementById("myLineChart");
var myLineChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: label,
    datasets: [{
      label: "Line",
      data: data,
      percent_data: per_data_from_html,
    }],
  },
    tooltips: {
      callbacks: {
        label: function(tooltipItem, chart) {
          var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || '';
          return datasetLabel + ': ₹ ' + number_format(tooltipItem.yLabel)+' ('+ (chart.datasets[tooltipItem.datasetIndex].percent_data[tooltipItem.datasetIndex]);
        }
      }
    }
  }
});
2
  • 1
    will you please share a sample of label and data? Commented Sep 30, 2020 at 11:14
  • @WhiteHat, Thanks for your concern. I got the solution now. But I will still share my label and data. Commented Sep 30, 2020 at 11:34

1 Answer 1

1

By changing parameter passing through percent_data array from percent_data[tooltipItem.datasetIndex] to percent_data[tooltipItem.index].

tooltips: {
  enabled: true,
  callbacks: {
    label: function(tooltipItem, chart) {
      var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || '';
      return datasetLabel + ': ₹ ' + chart.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] + ' (' + chart.datasets[tooltipItem.datasetIndex].percent_data[tooltipItem.index] + ')%';
    }
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

This is giving me the same percent_data while hovering in each point.
change the return into this => return datasetLabel + ': ₹ ' + chart.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] + ' (' + chart.datasets[tooltipItem.datasetIndex].percent_data[tooltipItem.index] + ')%';
Thanks It is working for me. But I am curious to know what was the issue.
we changed datasetIndex => index while passing parameter to percent_data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.