Echarts是一个开源的可视化图表库,支持丰富的图表,官网中还有大量示例可以选择使用、参考。
其中比较有趣的就是calendar,calendar是一个坐标系,这个坐标系与一般的直角坐标系不同,日历坐标系是根据日历的布局来显示数据,显示的具体的形状由series中设置的类型决定。
对于日历坐标系的应用一些网站已经使用,github上的贡献统计就有根据每天的上传的代码显示不同的颜色,csdn中的成就页面中也有显示。
就类似于上图的效果,今天就来实现一下。
首先,创建一个元素用来放置图表。
<div id="calendar"></div>
然后,初始化echarts实例
const echartsInstance = echarts.init(document.getElementById('calendar'));
然后,创建数据,数据比较多使用函数创建用来模拟数据。
function createData(year) {
const date = +echarts.time.parse(year + '-01-01');
const end = +echarts.time.parse(+year + 1 + '-01-01');
const dayTime = 3600 * 24 * 1000;
const data = [];
for (let time = date; time < end; time += dayTime) {
data.push([
echarts.time.format(time, '{yyyy}-{MM}-{dd}', false),
Math.floor(Math.random() * 10000)
]);
}
return data;
}
接下来,配置配置项,calendar设置calendar坐标系,通过top、left、right设置坐标系的位置,通过cellSize设置单元格的大小。
visuaMap用来映射显示在calendar坐标系上的数据,series设置显示在坐标系上的系列,创建的data就配置给series对象的data属性。
heatmap系列的特点是根据数据的大小显示深浅不同的颜色。除了heatmap也可以用散点图,根据数据的大小显示不同大小的点。
const option = {
color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
calendar: {
top: 120,
left: 30,
right: 30,
cellSize: ['auto', 13],
range: '2022',
splitLine: {
show: false
},
itemStyle: {
borderWidth: 0.5
},
dayLabel:{
nameMap:'ZH'
},
monthLabel:{
nameMap:'ZH'
},
yearLabel: {
show: false
}
},
tooltip:{},
visualMap: [{
type: 'piecewise',
pieces: [{
value: 0,
color: '#f0f0f2'
}, {
min: 1,
max: 1000,
color: '#daf3f0'
}, {
min: 1001,
max: 5000,
color: '#cceeea'
}, {
min: 5001,
max: 6000,
color: '#99ddd4'
}, {
min: 6001,
max: 9000,
color: '#73c0de'
},{
min:9001,
color:'#73c0de'
}],
orient: 'horizontal',
left: 'center',
top: 65
}],
series:[{
type:'heatmap',
coordinateSystem: 'calendar',
data:createData('2022')
}]
};
最后,设置配置项到echarts实例上。
echartsInstance.setOption(option);
效果如下
不过上面的数据都紧密的挨在一起,不方便观看,因此,接下来需要设置其样式把每一个数据分隔开。
let option = {
//……
itemStyle:{
borderWidth: 0.5,
borderColor:'#fff',
borderWidth:10
}
}
在之前的代码的基础上添加itemStyle配置项,设置每个数据的borderWidth来分隔开每一个数据。
最终,完整的配置如下
option = {
tooltip: {},
visualMap: [{
type: 'piecewise',
pieces: [{
value: 0,
color: '#f0f0f2'
}, {
min: 1,
max: 1000,
color: '#daf3f0'
}, {
min: 1001,
max: 5000,
color: '#cceeea'
}, {
min: 5001,
max: 6000,
color: '#99ddd4'
}, {
min: 6001,
max: 9000,
color: '#73c0de'
}, {
min: 9001,
color: '#73c0de'
}],
orient: 'horizontal',
left: 'center',
top: 65
}],
calendar: {
top: 120,
left: 30,
right: 30,
cellSize: [20, 23],
range: '2022',
splitLine: {
show: false
},
itemStyle: {
borderWidth: 0.5,
borderColor:'#fff',
borderWidth:10
},
dayLabel:{
nameMap:'ZH'
},
monthLabel:{
nameMap:'ZH'
},
yearLabel: {
show: false
}
},
series: [{
type: 'heatmap',
coordinateSystem: 'calendar',
data: createData('2022')
}]
};
效果如下: