如何在 x 轴上格式化 Highcharts 中的日期?
How to format dates in Highcharts on x-axis?
我将日期存储在需要在图表的 x 轴上显示的数组中。如何设置日期格式以使其在 x 轴上正确呈现?
{
"xData": ["2020-10-01T19:30:00.000Z",
"2020-10-02T19:30:00.000Z",
"2020-10-03T19:30:00.000Z",
"2020-10-04T19:30:00.000Z",
"2020-10-05T19:30:00.000Z",
...
...
]
}
Highcharts.chart('container, {
chart: {
marginLeft: 40
},
title: {
text: ''
},
xAxis: {
categories: Date.UTC(xData),
},
yAxis: {
title: {
text: null
}
},
series: [{
data: dataset.data,
}]
});
如果您想对类别使用 x 轴,请将您的日期字符串映射到一个数组,其中包含具有您想要的格式的字符串。
xAxis: {
categories: dataset.xData.map(date => {
return Highcharts.dateFormat('%Y-%m-%d', new Date(date).getTime());
})
}
现场演示: http://jsfiddle.net/BlackLabel/oL1ncjes/
API参考:https://api.highcharts.com/class-reference/Highcharts#.dateFormat
但我认为更合适的解决方案是以 [x, y]
格式创建数据,使用日期时间 x 轴类型和标签格式:
const processedData = dataset.data.map((dataEl, i) => {
return [new Date(dataset.xData[i]).getTime(), dataEl] // x, y format
});
Highcharts.chart('container', {
...,
xAxis: {
type: 'datetime',
labels: {
format: '{value:%Y-%m-%d}'
}
},
series: [{
data: processedData
}]
});
我将日期存储在需要在图表的 x 轴上显示的数组中。如何设置日期格式以使其在 x 轴上正确呈现?
{
"xData": ["2020-10-01T19:30:00.000Z",
"2020-10-02T19:30:00.000Z",
"2020-10-03T19:30:00.000Z",
"2020-10-04T19:30:00.000Z",
"2020-10-05T19:30:00.000Z",
...
...
]
}
Highcharts.chart('container, {
chart: {
marginLeft: 40
},
title: {
text: ''
},
xAxis: {
categories: Date.UTC(xData),
},
yAxis: {
title: {
text: null
}
},
series: [{
data: dataset.data,
}]
});
如果您想对类别使用 x 轴,请将您的日期字符串映射到一个数组,其中包含具有您想要的格式的字符串。
xAxis: {
categories: dataset.xData.map(date => {
return Highcharts.dateFormat('%Y-%m-%d', new Date(date).getTime());
})
}
现场演示: http://jsfiddle.net/BlackLabel/oL1ncjes/
API参考:https://api.highcharts.com/class-reference/Highcharts#.dateFormat
但我认为更合适的解决方案是以 [x, y]
格式创建数据,使用日期时间 x 轴类型和标签格式:
const processedData = dataset.data.map((dataEl, i) => {
return [new Date(dataset.xData[i]).getTime(), dataEl] // x, y format
});
Highcharts.chart('container', {
...,
xAxis: {
type: 'datetime',
labels: {
format: '{value:%Y-%m-%d}'
}
},
series: [{
data: processedData
}]
});