Highcharts 动态图(实时更新图表)详解
Highcharts 的动态图(也叫实时图表)是其最强大的功能之一,能够在不刷新页面的情况下平滑添加、修改或删除数据点,并带动画效果。非常适合:
- 实时监控(如服务器CPU、温度传感器、IoT 数据)
- 股票/加密货币价格走势
- 网站访问量统计
- 仪表盘系统
- 任何需要持续更新的数据场景
核心动态更新 API
| 方法 | 用途 | 示例代码 |
|---|---|---|
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>
const chart = Highcharts.chart('container', {
chart: {
type: 'spline', // 推荐 spline 或 areaspline,曲线更平滑
animation: Highcharts.svg, // 开启动画
marginRight: 10,
events: {
load: function () {
const series = this.series[0];
let x = (new Date()).getTime(); // 初始时间
setInterval(function () {
x += 1000; // 每秒递增
const y = Math.random() * 100 + 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: 150,
plotLines: [{ value: 100, color: 'red', dashStyle: 'ShortDash', width: 2 }]
},
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 () {
// 初始化最近 20 个点
const data = [];
const time = (new Date()).getTime();
for (let i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random() * 100 + 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 + 50], true, true);
}, 2000);
}
3. 从后端接口实时获取数据(Ajax 示例)
setInterval(function () {
fetch('/api/realtime') // 替换为你的接口地址
.then(res => res.json())
.then(data => {
const x = (new Date()).getTime();
chart.series[0].addPoint([x, data.cpu], true, true);
chart.series[1].addPoint([x, data.memory], true, true);
})
.catch(err => console.error('获取数据失败', err));
}, 5000);
4. 其他实用技巧
- 动态切换图表类型(比如从折线切换到柱状):
document.getElementById('btn').onclick = function () {
chart.update({
chart: { type: chart.options.chart.type === 'spline' ? 'column' : 'spline' }
});
};
- 性能优化(大数据量):
- 引入 Boost 模块(支持百万级点):
html ¨K12K - 限制显示点数(shift: true)
- 关闭动画:
animation: false
5. 推荐实时图表类型
spline/areaspline:最常用,曲线平滑line:简单直线column:柱子生长动画很酷scatter/bubble:轨迹追踪gauge(仪表盘):需额外模块
Highcharts 的动态更新性能极佳,几乎所有图表类型都支持实时动画。
如果你有具体需求,比如:
- 多条曲线实时监控
- WebSocket 实时推送
- 股票K线实时图(Highcharts Stock)
- 在 Vue/React 中封装动态图
告诉我你的场景,我可以提供完整可运行的代码示例!