You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ECharts多Grid场景下如何实现共享对齐的时间型X轴?

解决ECharts多Grid时序图X轴对齐问题

不用折腾单Grid的复杂方案,最简便的方式是强制所有X轴使用统一的时间范围,让ECharts不再自动为每个Grid单独计算X轴的min/max。

具体实现步骤

  1. 遍历所有系列的数据集,提取所有时间点并转换为时间戳,找出全局最早和最晚的时间边界
  2. 将这个全局时间范围赋值给每个X轴的min和max属性

修改后的完整配置示例

// 先计算全局时间范围
const allData = [
  ...option.series[0].data,
  ...option.series[1].data,
  ...option.series[2].data,
  ...option.series[3].data
];
const timestamps = allData.map(item => new Date(item[0]).getTime());
const globalMin = Math.min(...timestamps);
const globalMax = Math.max(...timestamps);

// 最终图表配置
option = {
  tooltip: {
    trigger: 'axis'
  },
  grid: [
    { top: '10%', height: '18%' },
    { top: '30%', height: '18%' },
    { top: '50%', height: '18%' },
    { top: '70%', height: '18%' },
  ],
  xAxis: [
    { type: 'time', gridIndex: 0, min: globalMin, max: globalMax },
    { type: 'time', gridIndex: 1, min: globalMin, max: globalMax },
    { type: 'time', gridIndex: 2, min: globalMin, max: globalMax },
    { type: 'time', gridIndex: 3, min: globalMin, max: globalMax },
  ],
  yAxis: [
    { type: 'value', gridIndex: 0 },
    { type: 'value', gridIndex: 1 },
    { type: 'value', gridIndex: 2 },
    { type: 'value', gridIndex: 3 },
  ],
  series: [
    { type: 'line', name: 'line1', xAxisIndex: 0, yAxisIndex: 0, data: [['2012-03-01 05:06', 120], ['2012-03-01 05:07', 132], ['2012-03-01 05:10', 432]] },
    { type: 'line', name: 'line2', xAxisIndex: 1, yAxisIndex: 1, data: [['2012-03-01 05:06', 220], ['2012-03-01 05:07', 182], ['2012-03-01 05:08', 482]] },
    { type: 'line', name: 'line3', xAxisIndex: 2, yAxisIndex: 2, data: [['2012-03-01 05:06', 150], ['2012-03-01 05:07', 232], ['2012-03-01 05:11', 432]] },
    { type: 'line', name: 'line4', xAxisIndex: 3, yAxisIndex: 3, data: [['2012-03-01 05:06', 320], ['2012-03-01 05:07', 332], ['2012-03-01 05:08', 432]] },
  ]
};

// 渲染或更新图表
myChart.setOption(option);

额外说明

  • 如果数据是动态加载的,只需要在数据获取完成后重新计算一次全局时间范围,再调用setOption更新图表即可
  • 这种方式完全保留了多Grid独立Y轴的优势,代码量远小于单Grid手动调整的方案,维护成本更低

内容的提问来源于stack exchange,提问作者miyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 03:13:17