gpt4 book ai didi

chart.js - ChartJS - 将图例标题添加到工具提示标题中

转载 作者:行者123 更新时间:2023-12-05 02:48:28 25 4
gpt4 key购买 nike

您能告诉我要在 chartJS 选项中添加什么以使图例标题也包含在工具提示标题中吗?在随附的屏幕截图中,您可以看到我想在工具提示的标题中添加年份提醒。

                 var chartdata = {
labels: ['Jan','Fev','Mar','Avr','Mai','Jui','Jui','Aou','Sep','Oct','Nov','Dec'],
datasets: JSON.parse('<?php echo $datasets ?>')
};

var graphTarget = $("#graphCanvas");

var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata,
options: {
responsive: true,
legend: {
position: 'right',
},
title: {
display: true,
text: 'Consommation électrique'
},
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function(tooltipItems, data) {
return tooltipItems.yLabel + ' kW';
}
}
},
scales: {
yAxes: [{
ticks: {
// Includes 'kW' after the value
callback: function(value, index, values) {
return value + ' kW';
}
}
}]
}
}
});

谢谢!

graph look

最佳答案

你可以定义一个tooltips title callback如下:

tooltips: {
callbacks: {
title: (tooltipItems, data) => tooltipItems[0].xLabel + ' ' + data.datasets[tooltipItems[0].datasetIndex].label,
...
}

请查看您修改后的代码,看看它是如何工作的。

var barGraph = new Chart('chart', {
type: 'bar',
data: {
labels: ['Jan', 'Fev', 'Mar', 'Avr', 'Mai', 'Jui', 'Jui', 'Aou', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [{
label: '2019',
data: [3, 4, 5, 2, 3, 2, 3, 4, 1, 2, 4, 5],
backgroundColor: 'blue'
},
{
label: '2020',
data: [3, 4, 1, 2, 4, 5, 3, 4, 5, 2, 3, 2],
backgroundColor: 'green'
}
]
},
options: {
responsive: true,
legend: {
position: 'right',
},
title: {
display: true,
text: 'Consommation électrique'
},
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
title: (tooltipItems, data) => tooltipItems[0].xLabel + ' ' + data.datasets[tooltipItems[0].datasetIndex].label,
label: tooltipItems => tooltipItems.yLabel + ' kW'
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: value => value + ' kW'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="chart" height="100"></canvas>

关于chart.js - ChartJS - 将图例标题添加到工具提示标题中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64466920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com