Chart.js X轴格式化程序更改图表中显示的值 [英] Chart.js xaxis formatter changes the value shown in the chart
本文介绍了Chart.js X轴格式化程序更改图表中显示的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个简单的可视化,显示过去24小时内温度的演变。如图所示。
在x轴上,我正在显示小时数,并尝试将其格式设置为10-&>10:00,依此类推。
但是,当我在选项中包括ticks.callback时,聊天显示如下:它总是在0:00开始,而正确的聊天在这个特定时间从12开始。
ticks: {
callback: function(value, index, ticks) {
return `${value}:00`;
}
}
如您所见,我已经能够设置y轴的格式,但是x轴有些不同。
这是图表的全部配置,以防出现错误:
const labels = this.extractLabels(this.props.data);
const dataPoints = this.extractData(this.props.data);
const data = {
labels: labels,
datasets: [{
label: 'Avg. Temperature',
data: dataPoints,
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
};
const options = {
scales: {
y: {
beginAtZero: true,
grace: '5%',
title: {
display: true,
text: 'Temperature',
font: {
size: 16
}
},
ticks: {
callback: function(value, index, ticks) {
return value + ' ºC';
}
}
},
x: {
title: {
display: true,
text: 'Date',
font: {
size: 16
}
},
ticks: {
callback: function(value, index, ticks) {
return `${value}:00`;
}
}
}
}
};
const config = {
type: 'line',
data: data,
options: options,
};
this.temperatureChart = new Chart(this.chartRef.current, config);
推荐答案
根据docs中的提示:
类别轴是折线图和条形图的默认x轴,它使用索引作为内部数据格式。要访问标签,请使用this.getLabelForValue(Value)。接口名:getLabelForValue
因此,要获得正确的显示值,您的回调需要如下所示:
ticks: {
callback: function(value, index, ticks) {
return `${this.getLabelForValue(value)}:00`;
}
}
这篇关于Chart.js X轴格式化程序更改图表中显示的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文