有一种特殊类型的轴 - time,它可以用来自动缩放 X 轴标签。
时间刻度用于显示时间和日期。
在构建它的刻度时,它会根据刻度的大小自动计算最舒适的单位。
labels 选项不是必需的,data 应重新整形为 { x: new Date('2020-12-01'), y: 123 } 的数组。
const data = [
{ x: new Date('2020-12-01'), y: 123 },
{ x: new Date('2020-12-02'), y: 134 },
{ x: new Date('2020-12-03'), y: 154 },
// etc.
],
X轴也需要配置为使用time类型(好像不会自动检测到)
var myChart = new Chart(canvas_link, {
type: 'bar',
data: {
// labels: xvalues, (not needed)
datasets: [{
label: area_option,
data: data, // note: should be new data not the old one
backgroundColor: 'rgba(255, 99, 132, 1)',
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
}],
}
}
})
你可以找到我的代码here。
已更新:X 轴仅显示季度/月。
添加unit: 'quarter'或unit: 'month'可以按季度或月份对X轴标签进行分组。
其他支持的单位可以在docs找到。
更新版本可以找到here
var myChart = new Chart(canvas_link, {
type: 'bar',
data: {
datasets: [{
data: data,
label: 'Data',
backgroundColor: 'rgba(255, 99, 132, 1)',
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
display: true,
scaleLabel: {
display: true,
labelString: 'Date'
},
time: {
unit: 'quarter',
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
}],
}
}
})