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:
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!