ECharts Asynchronous Data Loading
ECharts typically sets data within the setOption
method. If we need to load data asynchronously, we can use tools like jQuery to fetch data asynchronously and then fill it into setOption
along with the configuration options.
echarts_test_data.json Data:
{
"data_pie": [
{"value": 235, "name": "Video Ads"},
{"value": 274, "name": "Affiliate Ads"},
{"value": 310, "name": "Email Marketing"},
{"value": 335, "name": "Direct Access"},
{"value": 400, "name": "Search Engines"}
]
}
Example
var myChart = echarts.init(document.getElementById('main'));
$.get('https://www.tutorialpro.org/static/js/echarts_test_data.json', function (data) {
myChart.setOption({
series: [
{
name: 'Access Sources',
type: 'pie', // Set chart type to pie chart
radius: '55%', // Pie chart radius, outer radius is 55% of the visible area size (smaller of container width and height).
data: data.data_pie
}
]
})
}, 'json')
If asynchronous loading takes some time, we can add a loading effect. ECharts provides a simple loading animation by default. Just call the showLoading
method to display it. After the data is loaded, call the hideLoading
method to hide the loading animation:
Example
var myChart = echarts.init(document.getElementById('main'));
myChart.showLoading(); // Enable loading effect
$.get('https://www.tutorialpro.org/static/js/echarts_test_data.json', function (data) {
myChart.hideLoading(); // Hide loading effect
myChart.setOption({
series: [
{
name: 'Access Sources',
type: 'pie', // Set chart type to pie chart
radius: '55%', // Pie chart radius, outer radius is 55% of the visible area size (smaller of container width and height).
data: data.data_pie
}
]
})
}, 'json')
Dynamic Data Update
ECharts is data-driven, and changes in data drive changes in chart display, making dynamic data implementation extremely simple.
All data updates are achieved through setOption
. You just need to periodically fetch data and fill it into setOption
without considering what changes the data has undergone. ECharts will find the differences between the two sets of data and animate the changes appropriately.
Example
var base = +new Date(2014, 9, 3);
var oneDay = 24 * 3600 * 1000;
var date = [];
var data = [Math.random() * 150];
var now = new Date(base);
function addData(shift) {
now = [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/');
date.push(now);
data.push((Math.random() - 0.4) * 10 + data[data.length - 1]);
if (shift) {
date.shift();
data.shift();
}
now = new Date(+new Date(now) + oneDay);
}
for (var i = 1; i < 100; i++) {
addData();
}
option = {
xAxis: {
type: 'category',
boundaryGap: false,
data: date
},
yAxis: {
boundaryGap: [0, '50%'],
type: 'value'
},
series: [
{
name: '成交',
type: 'line',
smooth: true,
symbol: 'none',
stack: 'a',
areaStyle: {
normal: {}
},
data: data
}
]
};
setInterval(function () {
addData(true);
myChart.setOption({
xAxis: {
data: date
},
series: [{
name: '成交',
data: data
}]
});
}, 500);