ChartJS中合并双API折线与气泡图时气泡日期错位问题
问题核心
折线图依赖字符串格式的labels对应X轴,气泡图则使用Date对象作为x值,两种数据类型在Chart.js的时间轴上无法正确匹配,导致气泡位置错位。同时折线图的纯数值数组数据与气泡图的{x,y}对象数据,X轴对齐逻辑不一致。
修复方案
统一两个数据集的X轴数据格式,均使用{x: Date对象, y: 数值}的结构,移除依赖labels的配置,让时间轴直接基于数据中的x值对齐。
1. 重构折线图数据
将第一个API返回的日期和价格数据,转换为{x,y}格式的对象数组:
const lineData = data.data.map(d => ({ x: new Date(d.date), y: d.AAPL }));
2. 删除labels配置
由于现在两个数据集都自带X轴信息,不再需要data.labels字段,直接删除该配置项。
3. 保留气泡图数据处理逻辑
气泡图的{x,y}格式无需修改,确保lastDate转换为Date对象即可。
完整修复代码
fetch("link_to_first_api_json") .then(response => response.json()) .then(data => { const lineData = data.data.map(d => ({ x: new Date(d.date), y: d.AAPL })); fetch("link_to_second_api_json") .then(response => response.json()) .then(bubbleApiData => { const bubbleData = bubbleApiData.AAPL.map(d => ({ x: new Date(d.lastDate), y: d.lastPrice })); const ctx = document.getElementById("myCharttt").getContext("2d"); new Chart(ctx, { type: "line", data: { datasets: [ { label: "AAPL", data: lineData, borderColor: "red" }, { label: "Bubble Chart", data: bubbleData, backgroundColor: "blue", type: "bubble" } ] }, options: { scales: { xAxes: [{ type: "time", time: { unit: "day" } }], yAxes: [{ ticks: { beginAtZero: true } }] } } }); }) .catch(error => console.error(error)); }) .catch(error => console.error(error));
补充说明
- 确保API返回的日期格式为
YYYY-MM-DD这类Chart.js可直接解析的格式,若格式特殊,需在创建Date对象时做适配处理。 - 时间轴
time.unit设为"day",与数据的日度频率匹配,保证对齐精度。
内容的提问来源于stack exchange,提问作者kie_codes
相关产品推荐
相关产品推荐

