search
HomeWeb Front-endJS TutorialHow to implement real-time data updates in ECharts

How to implement real-time data updates in ECharts

ECharts is an open source visual chart library that supports various chart types and rich data visualization effects. In actual scenarios, we often need to display real-time data, that is, when the data source changes, the chart can be updated immediately and present the latest data.

So, how to implement real-time data updates in ECharts? The following is a specific code demonstration example.

First, we need to introduce ECharts’ js files and theme styles:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>ECharts实时数据更新</title>
    <!--引入ECharts的js文件-->
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/4.7.0/echarts.min.js"></script>
    <!--引入ECharts主题样式-->
    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/echarts/4.7.0/theme/macarons.min.js"></script>
</head>
<body>
    <!--ECharts图表容器-->
    <div id="chart" style="width: 800px;height: 600px;"></div>
</body>
</html>

Next, we need to define a data source to simulate changing real-time data:

// 模拟实时数据
var data = [120, 132, 101, 134, 90, 230, 210];
setInterval(function() {
    // 修改数据
    data.shift();
    data.push(Math.random() * 200);
}, 3000);

Among them, the setInterval function is used to update the data every 3 seconds, and Math.random() * 200 generates a random number to simulate changes in the data. Of course, in practical applications, we need to obtain and process data according to specific circumstances.

Next, we need to define an ECharts chart instance and render the chart to the HTML page:

// 定义ECharts图表实例
var chart = echarts.init(document.getElementById('chart'),'macarons');

// 渲染图表
chart.setOption({
    title: {
        text: 'ECharts实时数据更新演示',
        subtext: '数据源从左侧滚动',
        left: 'center'
    },
    xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
        type: 'value',
        axisLabel: {
            formatter: '{value} °C'
        }
    },
    series: [{
        name: '温度',
        type: 'line',
        data: data
    }]
});

In ECharts, we need to set various properties of the chart through the setOption function, including Titles, axes, data series, etc. In this example, we set an X-axis coordinate containing 7 days, the Y-axis coordinate is the temperature value, the data series is temperature data, and the type is a line chart. In addition, we used the macarons theme style to beautify the display effect of the chart.

Finally, we need to continuously update the chart data through the timer to achieve real-time data display:

// 定时更新数据
setInterval(function() {
    // 更新数据
    data.shift();
    data.push(Math.random() * 200);
    
    // 更新图表
    chart.setOption({
        series: [{
            data: data
        }]
    });
}, 3000);

In the timer, we use the shift function to change the first value of the data source Pop-up, the push function adds the generated random number to the end of the data source, realizing the transformation of the data. After that, we updated the data series of the ECharts chart through the setOption function to achieve real-time display of the chart.

To sum up, the above is a specific code example of how to implement real-time data update in ECharts. In actual use, we can adjust and optimize according to our actual needs.

The above is the detailed content of How to implement real-time data updates in ECharts. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software