Highcharts 散点图(Scatter Chart)详解
Highcharts 的散点图是最适合展示两个数值变量之间关系(如相关性、分布、聚类)的图表类型。每个数据点用一个标记(默认圆点)表示,支持自定义标记形状、大小、颜色,并可轻松扩展为气泡图(bubble)展示第三维度。
1. 基本散点图完整示例
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Highcharts 散点图示例</title>
<script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<div id="container" style="width: 900px; height: 600px; margin: 50px auto;"></div>
<script>
Highcharts.chart('container', {
chart: {
type: 'scatter', // 关键:设置为 'scatter'
zoomType: 'xy', // 允许鼠标拖拽缩放(强烈推荐)
backgroundColor: '#f8f9fa',
panning: true,
panKey: 'shift' // 按住 Shift 键拖动画布
},
title: {
text: '身高与体重关系散点图',
style: { fontSize: '20px', fontWeight: 'bold' }
},
subtitle: {
text: '模拟学生数据(n=100)'
},
xAxis: {
title: { text: '身高 (cm)' },
gridLineWidth: 1,
min: 145,
max: 205,
startOnTick: true,
endOnTick: true
},
yAxis: {
title: { text: '体重 (kg)' },
min: 35,
max: 110
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '身高:{point.x} cm<br>体重:{point.y} kg'
},
plotOptions: {
scatter: {
marker: {
radius: 6,
symbol: 'circle', // 可选:circle, square, diamond, triangle, triangle-down
states: {
hover: {
radiusPlus: 4,
lineWidthPlus: 2
}
}
},
jitter: { // 轻微抖动,避免点完全重叠
x: 0.05,
y: 0.05
}
}
},
series: [{
name: '男生',
color: '#7cb5ec',
data: [
[168, 62], [172, 68], [175, 72], [178, 78], [180, 82],
[182, 85], [185, 88], [188, 92], [170, 65], [173, 70]
// ... 可添加更多数据
]
}, {
name: '女生',
color: '#ff9999',
marker: {
symbol: 'triangle'
},
data: [
[158, 48], [160, 50], [162, 52], [165, 55], [168, 58],
[155, 45], [163, 53], [167, 57], [170, 60], [159, 49]
// ... 更多数据
]
}]
});
</script>
</body>
</html>
2. 多系列 + 不同标记样式示例
series: [
{
name: '组别A',
color: '#2caffe',
marker: { symbol: 'square', radius: 8 }
},
{
name: '组别B',
color: '#ff6b6b',
marker: { symbol: 'diamond', radius: 7 }
},
{
name: '组别C',
color: '#4ecdc4',
marker: { symbol: 'triangle-down' }
}
]
3. 添加回归趋势线(常见需求)
Highcharts 原生不带自动回归线,但可手动添加一条 line 系列作为趋势线:
// 假设已计算回归线数据(这里用示例点)
var trendline = [[150, 40], [200, 95]];
series: [
// ... 你的散点系列
{
type: 'line',
name: '趋势线',
data: trendline,
marker: { enabled: false },
dashStyle: 'ShortDash',
color: '#000000',
lineWidth: 2,
enableMouseTracking: false, // 不显示 tooltip
zIndex: 10
}
]
4. 扩展为气泡图(Bubble Chart)
只需引入 highcharts-more.js 并改类型:
<script src="https://code.highcharts.com/highcharts-more.js"></script>
chart: { type: 'bubble' },
series: [{
data: [
{ x: 165, y: 58, z: 20, name: '点1' }, // z 控制气泡大小
{ x: 175, y: 75, z: 35 },
// ...
]
}]
5. 常用配置速查
| 配置项 | 说明与推荐值 |
|---|---|
chart.type | ‘scatter’ |
chart.zoomType | ‘xy’(大数据量时必开) |
plotOptions.scatter.marker | radius / symbol / states(自定义点样式) |
plotOptions.scatter.jitter | { x: 0.05, y: 0.05 }(避免重叠) |
series.color | 指定系列颜色 |
series.marker.symbol | ‘circle’ / ‘square’ / ‘diamond’ / ‘triangle’ 等 |
6. 适用场景
- 相关性分析(身高-体重、温度-销量)
- 异常点检测
- 聚类展示(不同颜色/形状区分组别)
- 与气泡图结合展示第三维度
如果你需要:
- 大量数据点(上万点)的性能优化(boost 模块)
- 自动计算回归线并显示公式
- 动态添加散点
- 与箱线图(boxplot)组合
告诉我具体需求,我可以提供更针对性的完整代码示例!