Highcharts 动态图

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 中封装动态组件

告诉我你的应用场景,我可以提供完整可运行的代码示例!

文章已创建 3511

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部