如何用Apache Echarts实现X轴为时间的横向堆叠条形图
实现横向时间分段条形图(单一行展示不同时间段的店铺分配)
根据需求和参考效果,这里给出基于ECharts的可行实现方案,核心是将所有数据映射到同一Y轴位置,通过X轴的时间区间展示不同店铺的分配时段:
预处理数据
先将原始数据中的重复时间段合并(比如你数据里重复的14:00-14:15的Shop1),再将每个时间段转换为ECharts可识别的格式,同时固定Y轴取值,确保所有条形在同一行。
完整配置代码
const rawData = [ { from: "2024-12-01T13:15:00.0000000Z", to: "2024-12-01T13:30:00.0000000Z", bestShop: "Shop 1" }, { from: "2024-12-01T13:30:00.0000000Z", to: "2024-12-01T13:45:00.0000000Z", bestShop: "Shop 2" }, { from: "2024-12-01T13:45:00.0000000Z", to: "2024-12-01T14:00:00.0000000Z", bestShop: "Shop 3" }, { from: "2024-12-01T14:00:00.0000000Z", to: "2024-12-01T14:15:00.0000000Z", bestShop: "Shop 1" }, { from: "2024-12-01T14:15:00.0000000Z", to: "2024-12-01T14:30:00.0000000Z", bestShop: "Shop 2" }, { from: "2024-12-01T14:30:00.0000000Z", to: "2024-12-01T14:45:00.0000000Z", bestShop: "Shop 3" }, { from: "2024-12-01T14:45:00.0000000Z", to: "2024-12-01T15:00:00.0000000Z", bestShop: "Shop 1" }, { from: "2024-12-01T15:00:00.0000000Z", to: "2024-12-01T15:15:00.0000000Z", bestShop: "Shop 3" }, ]; // 为每个店铺分配专属颜色 const shopColors = { "Shop 1": "#5470c6", "Shop 2": "#91cc75", "Shop 3": "#fac858" }; // 转换数据格式:适配ECharts的bar系列,所有条形绑定同一Y轴位置 const processedData = rawData.map(item => ({ name: item.bestShop, value: [ new Date(item.from).getTime(), 0, new Date(item.to).getTime(), 1 // 控制条形高度,可按需调整 ], itemStyle: { color: shopColors[item.bestShop] } })); const option = { id: "shop_allocation", title: { text: "Stacked Horizontal Bar with Time", left: "center" }, height: 200, tooltip: { formatter: params => { const [start, _, end] = params.value; return ` <div>店铺:${params.name}</div> <div>时段:${new Date(start).toLocaleString()} - ${new Date(end).toLocaleString()}</div> `; } }, xAxis: { type: "time", axisLabel: { formatter: (value) => new Date(value).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}) } }, yAxis: { type: "category", data: ["店铺分配"], axisTick: {show: false}, axisLabel: {show: false}, axisLine: {show: false} }, series: [ { type: "bar", barWidth: 40, // 条形高度,可按需调整 data: processedData, label: { show: true, position: "top", formatter: params => params.name } } ] };
关键配置说明
- Y轴设置:将Y轴设为
category类型,仅保留一个分类项,隐藏轴刻度、标签和轴线,确保所有条形在同一行展示。 - 数据转换:把每个时段的起始/结束时间转为时间戳,作为条形的X轴区间,Y轴固定0-1的范围控制条形高度。
- 颜色映射:为每个店铺分配专属颜色,通过
itemStyle绑定,强化视觉区分。 - Tooltip优化:自定义提示内容,清晰展示店铺名称和时段信息。
内容的提问来源于stack exchange,提问作者dunct
相关产品推荐
相关产品推荐

