React中用SciChart绘制X轴为HH:MM:SS时间的图表问题
解决React中SciChart X轴时间显示错误及仅显示HH:MM:SS格式问题
问题分析
当前存在两个核心问题:
- X轴默认显示日期+时间,不符合仅展示
HH:MM:SS的需求 - 时间显示内容不正确,大概率是时间戳单位不匹配(SciChart的
DateTimeNumericAxis要求毫秒级时间戳,若你的plotLine.x是秒级戳则会显示错误日期)
解决方案
1. 自定义X轴标签格式,强制显示HH:MM:SS
替换默认的SmartDateLabelProvider为DateLabelProvider,指定固定格式:
import { DateTimeNumericAxis, DateLabelProvider, NumberRange, EAxisAlignment } from "scichart"; const xAxis = new DateTimeNumericAxis(wasmContext, { growBy: new NumberRange(0.1, 0.1), // 根据数据时间间隔调整,比如每秒一个点就设为1000(毫秒) defaultXStep: 1000, labelProvider: new DateLabelProvider({ formatting: { format: "HH:mm:ss", // 强制时分秒格式 locale: "zh-CN" // 可选,设置本地化 } }), axisAlignment: EAxisAlignment.Bottom, autoRange: EAutoRange.Never, drawMajorGridLines: false, drawMinorGridLines: false, }); sciChartSurface.xAxes.add(xAxis);
2. 修正时间戳单位(关键)
SciChart的DateTimeNumericAxis要求输入毫秒级时间戳,如果你的plotLine.x是秒级时间戳(比如1699999999),必须乘以1000转换:
// 处理时间数据:秒级转毫秒级 const totalPoints = plotLine.y.length; const xValues = Array.from({ length: totalPoints }, (_, i) => plotLine.x[i] * 1000); // 修正起止时间戳 const startDate = plotLine.x[0] * 1000; setXStart(startDate); const endDate = plotLine.x[plotLine.x.length - 1] * 1000; setXEnd(endDate); // 追加数据到系列 xyDataSeriesCollection[line.Key]?.appendRange(xValues, plotLine.y); // 手动设置X轴可视范围(确保起止时间正确) xAxis.visibleRange = new DateRange(startDate, endDate);
如果你的plotLine.x已经是毫秒级时间戳,直接使用即可:
const xValues = plotLine.x;
错误原因说明
SmartDateLabelProvider会根据X轴时间范围自动切换显示格式,当范围跨天或更宽时,会自动添加日期,无法固定为时分秒- 若时间戳单位错误(秒级而非毫秒级),SciChart会将其解析为1970年左右的日期,导致显示内容完全错误
内容的提问来源于stack exchange,提问作者Abin Baisil
相关产品推荐
相关产品推荐

