Heatmap implementation
Heatmap Implementation
A heatmap is a visualization method that displays data density through color variations, particularly suitable for revealing distribution patterns in large datasets. ECharts provides a powerful heatmap component that supports both Cartesian and geographic coordinate systems, offering flexibility to meet the needs of various scenarios.
Basic Heatmap Configuration
The simplest heatmap requires three key configuration items: the x-axis, y-axis, and data points. Each data point must include three dimensions: the x-coordinate, y-coordinate, and value. Here is a basic example:
option = {
tooltip: {},
grid: {
left: '3%',
right: '7%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'category',
data: ['Breakfast', 'Lunch', 'Dinner', 'Late-night']
},
visualMap: {
min: 0,
max: 10,
calculable: true,
orient: 'horizontal',
left: 'center',
bottom: '15%'
},
series: [{
name: 'Meal Heat',
type: 'heatmap',
data: [
[0, 0, 5], // Mon Breakfast
[0, 1, 7], // Mon Lunch
[0, 2, 3], // Mon Dinner
[0, 3, 1], // Mon Late-night
// Other data...
[6, 2, 8] // Sun Dinner
],
label: {
show: true
},
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}]
};
Data Format Processing
In real-world projects, raw data often requires processing before it can be used in a heatmap. Common data transformation methods include:
- Converting from a 2D array:
function convertToHeatmapData(matrix) {
const result = [];
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
result.push([i, j, matrix[i][j]]);
}
}
return result;
}
- Converting from an array of objects:
const rawData = [
{ day: 'Mon', meal: 'Breakfast', value: 5 },
{ day: 'Mon', meal: 'Lunch', value: 7 },
// ...
];
const xCategories = [...new Set(rawData.map(item => item.day))];
const yCategories = [...new Set(rawData.map(item => item.meal))];
const heatmapData = rawData.map(item => [
xCategories.indexOf(item.day),
yCategories.indexOf(item.meal),
item.value
]);
Visual Mapping Configuration
The visualMap
component controls how data values are mapped to visual elements (primarily colors). ECharts offers multiple visual mapping methods:
visualMap: {
type: 'piecewise', // Segmented
pieces: [
{ min: 0, max: 3, label: 'Low', color: '#d94e5d' },
{ min: 3, max: 6, label: 'Medium', color: '#eac736' },
{ min: 6, max: 10, label: 'High', color: '#50a3ba' }
],
orient: 'vertical',
left: 'right',
top: 'center'
}
Or using continuous mapping:
visualMap: {
type: 'continuous',
min: 0,
max: 10,
inRange: {
color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
}
}
Geographic Heatmap
ECharts supports displaying heatmaps on maps, which is particularly useful for geographic distribution data:
$.get('geoJSON/China.json', function(geoJson) {
echarts.registerMap('china', geoJson);
const option = {
tooltip: {
trigger: 'item',
formatter: '{b}: {c}'
},
visualMap: {
min: 0,
max: 1000,
text: ['High', 'Low'],
realtime: false,
calculable: true,
inRange: {
color: ['#50a3ba', '#eac736', '#d94e5d']
}
},
series: [{
name: 'Sales',
type: 'heatmap',
coordinateSystem: 'geo',
data: [
{name: 'Beijing', value: 923},
{name: 'Shanghai', value: 865},
// ...
],
pointSize: 10,
blurSize: 15
}]
};
myChart.setOption(option);
});
Performance Optimization Tips
When dealing with large datasets, heatmaps may encounter performance issues. Here are some optimization suggestions:
- Use progressive rendering:
series: [{
progressive: 1000,
progressiveThreshold: 10000
}]
- Reduce data precision:
function downsampleData(data, factor) {
const result = [];
for (let i = 0; i < data.length; i += factor) {
result.push(data[i]);
}
return result;
}
- Adjust heatmap point size and blur radius:
series: [{
pointSize: 5, // Smaller points
blurSize: 8 // Appropriate blur radius
}]
Enhanced Interactivity
ECharts heatmaps support rich interactive features:
- Data filtering:
visualMap: {
type: 'continuous',
range: [3, 7], // Only display data with values between 3-7
hoverLink: true // Show corresponding data on hover
}
- Region zooming:
dataZoom: [
{
type: 'slider',
xAxisIndex: 0,
filterMode: 'filter'
},
{
type: 'inside',
xAxisIndex: 0,
filterMode: 'filter'
}
]
- Custom tooltip:
tooltip: {
formatter: function(params) {
return `${params.seriesName}<br/>
${params.data[0]}: ${params.data[1]}<br/>
Value: ${params.data[2]}`;
}
}
Advanced Application Example
Combining a heatmap with a scatter plot can simultaneously display data distribution and specific values:
series: [
{
name: 'Heatmap',
type: 'heatmap',
data: heatmapData,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
},
{
name: 'Scatter',
type: 'scatter',
symbolSize: function(data) {
return Math.sqrt(data[2]) * 5;
},
data: heatmapData.filter(item => item[2] > threshold),
label: {
show: true,
formatter: function(params) {
return params.data[2];
}
}
}
]
Dynamic Data Updates
Heatmaps support dynamic data updates, making them suitable for real-time data visualization:
function updateHeatmap() {
const newData = generateNewData();
myChart.setOption({
series: [{
data: newData
}]
});
// Update visualMap range
const values = newData.map(item => item[2]);
myChart.setOption({
visualMap: {
min: Math.min(...values),
max: Math.max(...values)
}
});
}
setInterval(updateHeatmap, 2000);
Custom Rendering Effects
Custom effects can be achieved by modifying itemStyle
:
series: [{
itemStyle: {
borderColor: 'rgba(255, 255, 255, 0.8)',
borderWidth: 1,
shadowColor: 'rgba(0, 0, 0, 0.5)',
shadowBlur: 10
},
blurSize: 5,
pointSize: 15
}]
Multiple Heatmap Coordination
Multiple heatmaps can be coordinated using axisIndex
:
grid: [
{left: '5%', width: '40%', top: '10%', height: '80%'},
{right: '5%', width: '40%', top: '10%', height: '80%'}
],
xAxis: [
{gridIndex: 0, type: 'category', data: ['Q1', 'Q2', 'Q3', 'Q4']},
{gridIndex: 1, type: 'category', data: ['Group A', 'Group B', 'Group C', 'Group D']}
],
yAxis: [
{gridIndex: 0, type: 'category', data: ['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen']},
{gridIndex: 1, type: 'category', data: ['Product 1', 'Product 2', 'Product 3']}
],
series: [
{
type: 'heatmap',
data: data1,
xAxisIndex: 0,
yAxisIndex: 0
},
{
type: 'heatmap',
data: data2,
xAxisIndex: 1,
yAxisIndex: 1
}
]
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:地图(Map)实现
下一篇:原始类型与字面量类型