As the title explains, I am trying to create a report using chart.js to give the user a graphical representation of the data that they have searched for in the system, I am currently able to get the data to display on the canvas.
I have the data being provided to the JS function in a JSON format from the backend of the system. I have the main data that is building the pie chart with other data needing to be added to the tooltips to give further explanation on that data point.
How would I go about this as looking online hasn't given any viable result that has worked?
I have attached a simplified version of the code below with the data being displayed and how it is produced in the system.
var ctx = document.getElementById('myChart').getContext('2d');
var data = {
title: "Booking duration between 01/08/2023 and 29/03/2024",
labels: ["0 - 6 days", "7 - 13 days", "14 - 20 days", "21 - 27 days", "28 - 34 days"],
datasets: [{
data: [2126, 430, 51, 20, 44],
backgroundColor: ["#82B6EB", "#434348", "#94EE7E", "#F3A15E", "#8385E8"],
datalabels: ["79.6 %", "16.1 %", "1.91 %", "0.75 %", "1.65 %"],
databooking: ["( 2126 bookings)", "( 430 bookings)", "( 51 bookings)", "( 20 bookings)", "( 44 bookings)"],
hoverOffset: 20
}]
};
var myChart = new Chart(ctx, {
type: 'pie',
data: data,
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, chartData) {
var dataset = chartData.datasets[tooltipItem.datasetIndex];
var currentValue = dataset.data[tooltipItem.index];
var dataLabel = dataset.datalabels[tooltipItem.index];
var dataBooking = dataset.databooking[tooltipItem.index];
return 'Value: ' + currentValue + ' ' + dataLabel + ' ' + dataBooking;
},
title: function(tooltipItems, data) {
return data.title;
}
}
}
}
});
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js"></script>
<div id="_Chart">
<canvas id="myChart" style="width:1700px; max-height: 550px;"></canvas>
</div>
Note that with Chart.js v4, the
tooltipconfiguration needs to be placed insideoptions.plugins. The context passed to the tooltipcallbacksis described here.Your
callbackscould be written as follows:Please take a look at your amended code below and see how it works.