基于Apache ECharts的年份作为图例/视觉映射的日历热力图
嘿Raja,我之前刚好做过类似的多年份日历热力图需求,给你分享下具体的实现思路和代码,应该能帮你快速解决问题!
实现多年份日历热力图的核心方案
ECharts原生日历坐标系默认是单年份的,但我们可以通过多日历组件拼接+数据分组绑定的方式实现多年份展示,下面是具体步骤:
1. 先准备结构化的多年份数据
数据需要包含年份、日期和对应热力值,格式尽量清晰,方便后续分组处理:
const rawData = [ { year: 2021, date: '2021-01-05', value: 82 }, { year: 2021, date: '2021-03-12', value: 67 }, { year: 2022, date: '2022-05-20', value: 94 }, { year: 2022, date: '2022-10-01', value: 45 }, { year: 2023, date: '2023-07-15', value: 78 }, // ... 更多年份的数据 ];
2. 配置多个日历坐标系组件
给每个年份单独配置一个日历组件,通过grid相关属性控制它们的排列位置(横向/纵向都可以),保证布局整齐:
// 先按年份分组数据 const groupDataByYear = (data) => { const groups = {}; data.forEach(item => { if (!groups[item.year]) groups[item.year] = []; groups[item.year].push([item.date, item.value]); }); return groups; }; const groupedData = groupDataByYear(rawData); const years = Object.keys(groupedData);
3. 绑定数据到对应日历组件
每个年份的热力图系列对应一个日历组件的calendarIndex,这样数据就会精准渲染到对应的年份日历上:
完整配置示例
const option = { tooltip: { position: 'top', formatter: (params) => { const date = new Date(params.value[0]); return `${date.getFullYear()}年${date.getMonth()+1}月${date.getDate()}日<br/>热力值: ${params.value[1]}`; } }, // 统一的视觉映射,保证所有年份样式一致 visualMap: { min: 0, max: 100, type: 'continuous', orient: 'horizontal', left: 'center', bottom: 30, color: ['#c23531', '#d87a68', '#fff2e8'] }, // 生成对应年份的日历组件 calendar: years.map((year, index) => ({ top: 50, left: `${index * 33 + 1}%`, // 横向排列,每个日历占30%宽度 width: '30%', height: '70%', range: year, cellSize: ['auto', 'auto'], itemStyle: { borderWidth: 0.5, borderColor: '#eee' }, dayLabel: { fontSize: 10 }, monthLabel: { fontSize: 12, nameMap: 'cn' }, // 显示中文月份 yearLabel: { fontSize: 14, fontWeight: 'bold' } })), // 每个年份对应一个热力图系列 series: years.map((year, index) => ({ type: 'heatmap', coordinateSystem: 'calendar', calendarIndex: index, data: groupedData[year], label: { show: false }, emphasis: { itemStyle: { borderColor: '#000', borderWidth: 2 } } })) }; // 初始化图表 const myChart = echarts.init(document.getElementById('main')); myChart.setOption(option);
额外优化建议
- 如果年份较多,可以把横向排列改成纵向排列,调整
top和height参数即可 - 通过
calendar.cellSize可以自定义日期格子的大小,适配不同的页面布局 - 数据处理时要确保日期格式是ECharts能识别的(比如
YYYY-MM-DD) - 视觉映射可以根据需求改成分段式(
type: 'piecewise'),更适合分类展示
内容的提问来源于stack exchange,提问作者Raja Chaitanya Rekapalli
相关产品推荐
相关产品推荐

