chart.js 4.4.2 Chartjs-插件-数据标签
const chartCtr = document.querySelector('#temp-chart1') as HTMLCanvasElement;
new Chart(chartCtr, {
type: 'line',
plugins: [ChartDataLabels],
options: {
layout: {
padding: {
bottom: 10.15,
},
},
maintainAspectRatio: false,
animation: false,
plugins: {
// zoom: {
// pan: {
// // pan options and/or events
// enabled: true,
// mode: 'x',
// },
// limits: {
// // axis limits
// },
// zoom: {
// // zoom options and/or events
// },
// },
legend: {
display: false,
},
},
scales: {
x: {
adapters: {
date: {
locale: enUS,
},
},
type: 'time',
ticks: {
stepSize: 3,
major: {
enabled: true,
},
},
time: {
unit: 'hour',
tooltipFormat: 'HH:mm',
},
position: 'top',
},
yTemp: {
ticks: {
display: false,
},
grid: {
drawTicks: false,
},
border: {
display: false,
},
},
yPop: {
display: false,
max: getMaxValueWithPadding(),
},
yLev: {
display: false,
},
},
},
data: {
labels: forecast.map((row) => row.date),
datasets: [
{
label: 'temp every 3 hrs',
data: forecast.map((row) => row.temp),
yAxisID: 'yTemp',
datalabels: {
display: false,
},
},
{
label: 'probability of preciptation',
data: forecast.map((row) => row.pop),
yAxisID: 'yPop',
type: 'bar',
datalabels: {
anchor: 'end',
align: 'end',
font: {
weight: 'bold',
},
formatter: (value) => `${((value as number) * 100).toFixed()}%`,
},
},
{
label: '3h rain',
yAxisID: 'yLev',
data: forecast.map((row) => {
const sum = (row.rain ?? 0) + (row.snow ?? 0);
if (sum) return sum;
else return '';
}),
hidden: true,
},
],
},
});
我想获取每个条形上最后一个数据集(“3 小时雨”)的值。我使用数据标签插件将“降水概率”数据集的值放置在每个条上。我如何为“3hrain”做同样的事情?
我想通了!添加我的解决方案来帮助任何正在为此苦苦挣扎的人。格式化程序选项(数据标签插件)接受两个参数。价值和背景。上下文变量有一个名为 dataIndex 的属性,它返回数据集中值的索引。利用这一点,您可以返回数据集的相关索引,并在使用不同的数据集时挑选您可能感兴趣的其他数据。
formatter: (value, context) => {
const bar = forecast[context.dataIndex];
const sum = (bar.rain ?? 0) + (bar.snow ?? 0);
if (sum)
return `${sum} mm/h\n${((value as number) * 100).toFixed()}%`;
else return `${((value as number) * 100).toFixed()}%`;
},
https://chartjs-plugin-datalabels.netlify.app/guide/options.html#option-context