Highcharts 动态图(实时更新图表)详解
Highcharts 的动态图(也称为实时图表)是其最受欢迎的功能之一,能够在页面不刷新的情况下,通过 JavaScript 动态添加、修改或删除数据点,并带有平滑动画效果。非常适合:
- 实时监控系统(CPU、内存、温度、流量等)
- 股票/加密货币价格走势
- IoT 传感器数据展示
- 网站访问统计
- 任何需要持续更新数据的场景
核心动态更新方法
| 方法 | 用途 | 示例代码 |
|---|---|---|
series.addPoint(point, redraw?, shift?, animation?) | 添加单个新数据点 | series.addPoint([x, y], true, true, true) |
series.setData(data, redraw?) | 替换整个系列数据 | series.setData(新数组) |
point.update(value, redraw?) | 更新单个现有数据点 | points[0].update(新值) |
chart.addSeries(options) | 添加新系列 | chart.addSeries({name: '新系列', data: [...]}) |
series.remove(redraw?) | 删除系列 | chart.series[0].remove() |
chart.update(options) | 批量修改图表配置(如切换类型) | chart.update({chart: {type: 'column'}}) |
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: 500px; margin: 50px auto;"></div>
<script>
Highcharts.chart('container', {
chart: {
type: 'spline', // 推荐 spline 或 areaspline,曲线更平滑
animation: Highcharts.svg,
marginRight: 10,
events: {
load: function () {
const series = this.series[0];
setInterval(function () {
const x = (new Date()).getTime(); // 当前时间戳
const y = Math.random() * 80 + 20; // 模拟随机数据
series.addPoint([x, y], true, true, true);
// 参数说明:
// [x, y] : 新数据点
// true : 立即重绘
// true : shift - 超出显示范围时自动删除最旧点
// true : 开启动画
}, 1000); // 每秒更新一次
}
}
},
time: { useUTC: false }, // 使用本地时间
title: { text: '实时数据监控仪表盘' },
subtitle: { text: '每秒自动更新' },
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
labels: { format: '{value:%H:%M:%S}' }
},
yAxis: {
title: { text: '数值' },
min: 0,
max: 120,
plotLines: [{
value: 80,
color: '#ff0000',
width: 2,
dashStyle: 'Dash',
label: { text: '警戒线' }
}]
},
tooltip: {
formatter: function () {
return '<b>' + Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '</b><br/>' +
'数值: <b>' + this.y.toFixed(2) + '</b>';
}
},
legend: { enabled: false },
exporting: { enabled: false },
series: [{
name: '实时数据',
color: '#7cb5ec',
data: (function () {
// 初始化显示最近 30 个点
const data = [];
const time = (new Date()).getTime();
for (let i = -29; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random() * 80 + 20
});
}
return data;
}())
}]
});
</script>
</body>
</html>
2. 多系列实时更新(常见监控场景)
load: function () {
const chart = this;
setInterval(function () {
const x = (new Date()).getTime();
chart.series[0].addPoint([x, Math.random() * 100], true, true);
chart.series[1].addPoint([x, Math.random() * 60 + 20], true, true);
chart.series[2].addPoint([x, Math.random() * 40 + 40], true, true);
}, 1500);
}
3. 从后端接口获取真实数据(Ajax 示例)
setInterval(function () {
fetch('/api/sensor-data') // 替换为你的真实接口
.then(response => response.json())
.then(data => {
const x = (new Date()).getTime();
chart.series[0].addPoint([x, data.temperature], true, true);
chart.series[1].addPoint([x, data.humidity], true, true);
});
}, 5000); // 每5秒请求一次
4. 其他实用技巧
- 动态切换图表类型(按钮切换折线 ↔ 柱状):
document.getElementById('switchBtn').addEventListener('click', function () {
const newType = chart.options.chart.type === 'spline' ? 'column' : 'spline';
chart.update({ chart: { type: newType } });
});
- 性能优化建议(大数据量时):
- 引入 Boost 模块支持百万级点:
html ¨K12K - 使用
shift: true限制显示点数 - 关闭动画:
animation: false
5. 推荐实时图表类型
spline/areaspline:最常用,视觉平滑line:简单高效column:柱子生长动画很酷scatter/bubble:适合轨迹追踪gauge(仪表盘):需额外模块
Highcharts 的动态更新性能极佳,几乎所有图表类型都支持实时动画,是构建专业仪表盘的首选。
如果你有具体需求,比如:
- 多条曲线实时监控
- WebSocket 实时推送
- 股票K线实时图(Highcharts Stock)
- 在 Vue/React 中封装动态组件
告诉我你的应用场景,我可以提供完整可运行的代码示例!