Highcharts 动态图(Dynamic Charts)详解
Highcharts 的最大优势之一就是支持实时动态更新图表,非常适合监控仪表盘、股票走势、传感器数据、实时统计等场景。你可以通过 JavaScript 动态添加/删除数据点、系列,甚至修改整个配置,而图表会平滑动画过渡。
常见动态效果
- 实时添加新数据点(最常用)
- 更新现有数据点
- 添加/移除整个系列
- 动态切换图表类型
- 结合 setInterval 或 WebSocket 实现真·实时更新
1. 基本实时更新示例(每秒添加一个点)
以下是一个完整的动态折线图示例,每秒随机添加一个新数据点,并自动移除旧数据保持显示最近 20 个点:
<!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: 500px; margin: 50px auto;"></div>
<script>
Highcharts.chart('container', {
chart: {
type: 'spline',
animation: Highcharts.svg, // 开启动画
marginRight: 10,
events: {
load: function () {
// 获取系列对象
var series = this.series[0];
var count = 0;
// 每秒更新一次
setInterval(function () {
var x = (new Date()).getTime(), // 当前时间(毫秒)
y = Math.random() * 100; // 随机值 0-100
series.addPoint([x, y], true, true); // 添加点,redraw,shift(移除旧点)
count++;
}, 1000);
}
}
},
time: {
useUTC: false // 使用本地时间
},
title: {
text: '实时随机数据监控'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: { text: '数值' },
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
headerFormat: '<b>{series.name}</b><br/>',
pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}'
},
legend: { enabled: false },
exporting: { enabled: false },
series: [{
name: '随机数据',
data: (function () {
// 初始化 20 个历史点
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random() * 100
});
}
return data;
}())
}]
});
</script>
</body>
</html>
关键方法说明:
series.addPoint([x, y], redraw, shift, animation)- redraw: true → 立即重绘
- shift: true → 当点数超出限制时移除最旧的点
chart.events.load→ 图表加载完成后执行定时器
2. 动态更新现有数据点(非添加)
// 更新第一个系列的第5个点
chart.series[0].points[4].update(newYValue);
// 更新整个系列数据
chart.series[0].setData([新数组]);
3. 多系列实时更新示例
load: function () {
var chart = this;
setInterval(function () {
var x = (new Date()).getTime();
chart.series[0].addPoint([x, Math.random() * 100], true, true);
chart.series[1].addPoint([x, Math.random() * 50 + 50], true, true);
}, 2000);
}
4. 动态添加/移除系列
// 添加新系列
chart.addSeries({
name: '新系列',
data: [[x1,y1], [x2,y2]]
});
// 移除第一个系列
chart.series[0].remove();
5. 结合外部数据源(Ajax 示例)
setInterval(function () {
fetch('/api/latest-data')
.then(response => response.json())
.then(data => {
chart.series[0].addPoint([data.time, data.value], true, true);
});
}, 5000);
6. 性能优化建议(大数据量时)
- 使用
Highcharts.boost.js模块(支持数十万点渲染) - 限制显示点数(shift: true)
- 关闭不必要动画:
animation: false - 使用
chart.update()批量修改配置
7. 其他动态效果
- 动态切换类型:
chart.update({ chart: { type: 'column' } });
- 响应式 + 动态数据:结合
responsive规则
动态图是 Highcharts 的强项,几乎所有图表类型(折线、柱状、区域、散点等)都支持实时更新。
如果你需要:
- 股票K线实时图(需 Stock 模块)
- 仪表盘动态指针
- WebSocket 实时推送
- Vue/React 中的动态更新封装
告诉我具体应用场景,我可以提供更完整的代码示例!