You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免ApexCharts更新Series时自动重置缩放与平移状态

解决ApexCharts实时更新数据时视图自动重置的问题

当使用ApexCharts展示实时数据,每次调用updateSeries()追加新数据点时,图表会自动重置缩放和平移状态,导致用户无法持续查看历史数据区域。

核心解决方案:使用appendData()替代updateSeries()

ApexCharts提供了专门的appendData() API,用于追加新数据点且不会重置当前图表视图,完美适配实时数据更新场景。

修改后的示例代码

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>Refreshing Apex Chart</title>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
</head>
<body>

<div>
    <h5 class="card-title" id="chartTitle">Refreshing Apex Chart | <span id="lastUpdate">Pending</span></h5>
    <div id="chart"></div>
</div>

<script>

// Function to generate initial data points
function generateInitialData() {
    const data = [];
    const now = new Date();

    for (let i = 9; i >= 0; i--) {
        const time = new Date(now.getTime() - i * 1000).getTime();
        const value = Math.floor(Math.random() * 100); // Generate a random value
        data.push([time, value]);
    }
    return data;
}

// Initialize the chart data with 10 data points
let series = [{
    name: 'Sample Data Series',
    data: generateInitialData()
}];

// Function to add new data
function addData() {
    const newTime = new Date().getTime();
    const newValue = Math.floor(Math.random() * 100);
    // 使用appendData追加单条数据,保留当前视图
    chart.appendData([{
        data: [[newTime, newValue]]
    }]);

    // Update the last update time
    document.getElementById('lastUpdate').textContent = new Date().toLocaleTimeString('de-DE');
}

// Initialize the chart
let options = {
    series: series,
    chart: {
        height: 350,
        type: 'area',
    },
    stroke: {
        width: 2,
        curve: 'smooth',
    },
    xaxis: {
        type: 'datetime',
    },
    dataLabels: {
        enabled: false
    },
};

let chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();

// Update data every second
setInterval(addData, 1000);
</script>

</body>
</html>

备选方案:手动保存并恢复视图范围

如果因业务需求必须使用updateSeries(),可以在更新前保存当前x轴的视图范围,更新后再恢复:

function addData() {
    // 保存当前x轴的缩放/平移范围
    const currentXRange = chart.xaxis.getRange();
    
    const newTime = new Date().getTime();
    const newValue = Math.floor(Math.random() * 100);
    series[0].data.push([newTime, newValue]);

    // 更新系列数据,禁用不必要的重绘动画
    chart.updateSeries(series, {
        redrawPaths: false,
        animate: false
    });

    // 恢复之前的x轴视图范围
    chart.updateOptions({
        xaxis: {
            min: currentXRange.min,
            max: currentXRange.max
        }
    });

    document.getElementById('lastUpdate').textContent = new Date().toLocaleTimeString('de-DE');
}

说明

  • appendData()是官方推荐的实时数据追加方式,内部已处理视图保留逻辑,代码更简洁高效。
  • 备选方案通过手动控制x轴范围实现视图保留,适合需要自定义更新逻辑的场景。

内容的提问来源于stack exchange,提问作者gear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 20:12:50