使用Echarts3实现动态折线图

#1引入Echarts及地图文件

*1)下载Echarts JS库文件及地图文件

        Echarts库下载地址 http://echarts.baidu.com/download.html

 

#2绘制折线图

*1)准备DOM容器,并设置高度和宽度为100%


    
    


    

*2)准备虚构随机数据,实际由接口获取

var getData = [
    {"month":"2017-07","count":6},{"month":"2017-08","count":2},{"month":"2017-09","count":0},
    {"month":"2017-10","count":0},{"month":"2017-11","count":6},{"month":"2017-12","count":1},
    {"month":"2018-01","count":4},{"month":"2018-02","count":5},{"month":"2018-03","count":2},
    {"month":"2018-04","count":2},{"month":"2018-05","count":0},{"month":"2018-06","count":3},
    {"month":"2018-07","count":3},{"month":"2018-08","count":2},{"month":"2018-09","count":4},
    {"month":"2018-10","count":5},{"month":"2018-11","count":5},{"month":"2018-12","count":3},
    {"month":"2019-01","count":3},{"month":"2019-02","count":0},{"month":"2019-03","count":0}]

*3)基于准备好的dom,初始化echarts实例

​
var chart = echarts.init(document.getElementById('main'));

​

*4)指定图表的配置项

index = 7;
option = {
    tooltip : {
        trigger: 'axis'
    },
    xAxis : [{
        type : 'category',
        boundaryGap : false,
        data : function (){
            var list = [];
                for (var i = 0; i < index; i++) {
                    list.push(getData[i].month);
                }
                return list;
        }()
    }],
    yAxis : [{
        type : 'value'
    }],
    series : [{
        name:'',
        type:'line',
        smooth: true,
        data:function (){
            var list = [];
            for (var i = 0; i < index; i++) {
                list.push(getData[i].count);
            }
            return list;
        }()
    }]
};

*5)使用指定的配置项和数据显示图表

​
chart.setOption(option);

​

*6)使用定时器设置动态效果

	setInterval(function (){
		if (index == getData.length -1) {
			index = 0;
		}
		var data = option.series[0].data;
		data.shift();
		data.push(getData[index].count);
		option.xAxis[0].data.shift();
		option.xAxis[0].data.push(getData[index++].month);
		myChart.setOption(option);
	}, 2000);

#3完整代码及效果

*1)完整代码


    


    

*2)效果图

使用Echarts3实现动态折线图_第1张图片

*3)在线编辑

https://gallery.echartsjs.com/editor.html?c=xrFYmIEn2y&v=1

你可能感兴趣的:(Echarts)