I am trying to get these four data values from the array and I want to display them on the tooltip along with the % symbol at the end.
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: 'Net Profit Margin',
data:[, 18, 19, 21, 20,]
},
{
label: 'Gross Profit Margin',
data: [, 57, 54, 57, 59,]
},
]
},
and in the tooltip, I am trying to get the data so that I can display it by using callbacks.
tooltip: {
callbacks: {
label: function (tooltipItem) {
output = myChart.data.datasets[0].data[]
}
}
},
Now I want to know should I write in data[___] in order to get the first object when I hover on it.
Beside the tooltip label callback, you also need to define interaction mode 'dataset'.
options: {
interaction: {
mode: 'dataset'
},
plugins: {
tooltip: {
callbacks: {
label: context => context.label + ': ' + context.formattedValue + '%'
}
}
}
}
Please take a look at below runnable code and see how it works.
var myChart = new Chart('myChart', {
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
label: 'Net Profit Margin',
data: [18, 19, 21, 20]
},
{
label: 'Gross Profit Margin',
data: [57, 54, 57, 59]
},
]
},
options: {
interaction: {
mode: 'dataset'
},
plugins: {
tooltip: {
callbacks: {
label: context => context.label + ': ' + context.formattedValue + '%'
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>