Echarts运用

    echarts客户端写法:http://echarts.baidu.com/doc/example.html  ,下载echarts-2.0.4.jar包,把src里面的js引入到项目里,在放esl.js,echarts-map.js,

echarts-original-map.js,echarts-plain.js到js里面,如图:

 

      echarts服务端端写法:http://www.oschina.net/news/55407/echarts-java-1-0,下载ECharts-1.0.0.jargson-2.3.jarECharts-all.zip,里面有

ECharts-1.0.0-javadoc.jar,ECharts-1.0.0-sources.jar,都引入到jar文件里面。

 

echarts作图还是很简单的,想要在客户端写,要先定义一个div,例如:

<%@ page contentType="text/html;charset=UTF-8" language="java" import="java.util.*" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <script type="text/javascript" src="js/lib/esl.js"></script>
    <script type="text/javascript" src="js/lib/echarts-map.js"></script>
   <script type="text/javascript" src="js/lib/echarts-original-map.js"></script>
</head>
<body>
   <div id="min" style="height: 400px; width:800px; border:1px solid #ccc;padding:10px;"></div>
   <script type="text/javascript" languag="javascript">
      // 按需加载
        // Step:3 conifg ECharts's path, link to echarts.js from current page.
        // Step:3 为模块加载器配置echarts的路径,从当前页面链接到echarts.js,定义所需图表路径
        require.config({
            paths: {
                 echarts:'./js/echarts',
                  'echarts/chart/bar' : './js/echarts-map',
                  'echarts/chart/line': './js/echarts-map',
                  'echarts/chart/map' : './js/echarts-map'            }
        });
        // Step:4 require echarts and use it in the callback.
        // Step:4 动态加载echarts然后在回调函数中开始使用,注意保持按需加载结构定义图表路径
        require(
        [
            'echarts',
         'echarts/chart/bar',
         'echarts/chart/line',
         'echarts/chart/map'        ],
        //回调函数
        DrawEChart
        );

        //渲染ECharts图表
        function DrawEChart(ec) {
            //图表渲染的容器对象
            var chartContainer = document.getElementById("min");
            //加载图表
            var myChart = ec.init(chartContainer);
            myChart.setOption({
                //图表标题
                title: {
                    text: "ECharts简单线形图表及其配置展示实例", //正标题
                    link: "http://www.stepday.com", //正标题链接 点击可在新窗口中打开
                    x: "center", //标题水平方向位置
                    subtext: "From:http://www.stepday.com", //副标题
                    sublink: "http://www.stepday.com", //副标题链接
                    //正标题样式
                    textStyle: {
                        fontSize:24
                    },
                    //副标题样式
                    subtextStyle: {
                        fontSize:12,
                        color:"red"
                    }
            },
            //数据提示框配置
            tooltip: {
                trigger: 'axis' //触发类型,默认数据触发,见下图,可选为:'item' | 'axis' 其实就是是否共享提示框
            },
            //图例配置
            legend: {
                data: ['蒸发量', '降水量'], //这里需要与series内的每一组数据的name值保持一致
                y:"bottom"
            },
            //工具箱配置
            toolbox: {
                show: true, //是否显示工具箱
                feature: {
                    mark: false, // 辅助线标志,上图icon左数1/2/3,分别是启用,删除上一条,删除全部
                    dataView: { readOnly: false }, // 数据视图,上图icon左数8,打开数据视图
                    magicType: ['line', 'bar'],      // 图表类型切换,当前仅支持直角系下的折线图、柱状图转换,上图icon左数6/7,分别是切换折线图,切换柱形图
                    restore: true, // 还原,复位原始图表,上图icon左数9,还原
                    saveAsImage: true  // 保存为图片,上图icon左数10,保存
                }
            },
            calculable: true,
            //轴配置
            xAxis: [
                    {
                        type: 'category',
                        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                        name: "月份"
                    }
                ],
            //Y轴配置
            yAxis: [
                    {
                        type: 'value',
                        splitArea: { show: true },
                        name:"数值"
                    }
                ],
            //图表Series数据序列配置
            series: [
                    {
                        name: '蒸发量',
                        type: 'line',
                        data: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
                    },
                    {
                        name: '降水量',
                        type: 'line',
                        data: [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
                    }
                ]
        });
        }
     
   </script>

  <jsp:include page="/jsp/footer.jsp"></jsp:include>
</body>
</html>

 服务器端的写法:就是在后台传json数据

  例如:做个地图:http://echarts.baidu.com/doc/example/map1.html

/*
     * 获得地图json数据
     */
    @Action(value = "getMap", results = {
            @Result(name = "success", type = "json", params = {
     "root","chartsJson"
   }
) }) public String getMap(){ ItemStyle item=new ItemStyle(); item.normal().label(new Label().show(true)); item.emphasis().label(new Label().show(true)); Option option = new GsonOption(); option.title().subtext("数据来自国家统计局").x(X.center); option.tooltip().trigger(Trigger.item); option.legend().orient(Orient.vertical).x(X.left).data("新闻","论坛","博客","微博"); option.dataRange().min(0).max(2500).x(X.left).y(Y.bottom).calculable(true); option.toolbox().show(true).orient(Orient.vertical).x(X.right).y(Y.center).feature(Tool.saveAsImage); Map map1=new Map("新闻"); map1.mapType("china").selectedMode(SelectedMode.single).itemStyle(item); String[] citis={"北京","天津","上海","重庆","河北","河南","云南","辽宁","黑龙江","湖南","安徽","山东","新疆","江苏","浙江","江西","湖北","广西","甘肃","山西","内蒙古","陕西","吉林","福建","贵州","广东","青海","西藏","四川","宁夏","海南","台湾","香港","澳门"}; List<Data> list=new ArrayList<Data>(); for(String city:citis){ list.add(new Data(city,Math.round(Math.random()*1000))); } map1.data(list.toArray(new Data[0])); Map map2=new Map("论坛"); map2.mapType("china").selectedMode(SelectedMode.single).itemStyle(item); String[] citis2={"北京","天津","上海","重庆","河北","安徽","新疆","浙江","江西","山西","内蒙古","吉林","福建","广东","西藏","四川","宁夏","香港","澳门"}; List<Data> list2=new ArrayList<Data>(); for(String city:citis2){ list2.add(new Data(city,Math.round(Math.random()*1000))); } map2.data(list2.toArray(new Data[0])); Map map3=new Map("博客"); map3.mapType("china").selectedMode(SelectedMode.single).itemStyle(item); String[] citis3={"北京","天津","上海","广东","台湾","香港","澳门"}; List<Data> list3=new ArrayList<Data>(); for(String city:citis3){ list3.add(new Data(city,Math.round(Math.random()*1000))); } map3.data(list3.toArray(new Data[0])); Map map4=new Map("微博"); map4.mapType("china").selectedMode(SelectedMode.single).itemStyle(item); String[] citis4={"北京","天津","上海","广东","台湾","香港","澳门"}; List<Data> list4=new ArrayList<Data>(); for(String city:citis4){ list4.add(new Data(city,Math.round(Math.random()*1000))); } map4.data(list3.toArray(new Data[0])); option.series(map1,map2,map3,map4); str= option.toString(); chartsJson=JSONObject.fromObject(str); return SUCCESS; }

 

 在页面只需要得到这个json串就可以了。

$(function(){
           // Step:4 动态加载echarts然后在回调函数中开始使用,注意保持按需加载结构定义图表路径
    require(
      [
      'echarts',
      'echarts/chart/bar',
      'echarts/chart/line'
     ],
      
     function (ec) {
         // 基于准备好的dom,初始化echarts图表
         var myChart = ec.init(document.getElementById('getFocus')); 
         $.ajax({
         	url:"${path }echarts/getMap.action",
         	type:"get",
         	data:{},
         	dataType:"json",
         	timeout:30000,
         	cache:false,
         	success:function(data){
         		 // 为echarts对象加载数据 
         		myChart.setOption(data.chartsJson); 
         	}
         });
}
);
});

   想要在页面多加几个图,可以这个样子获取json:这样更加简便

<body>
   <div id="main" style="height: 400px; width:50%; border:1px solid #ccc;padding:10px;"></div>
   <div class="clear"></div>
   <div id="yulunList" style="height: 400px; width:50%; border:1px solid red;padding:10px;"></div>
   
    <script type="text/javascript" src="${basePath}js/lib/esl.js"></script>
    <script type="text/javascript" src="${basePath}js/lib/echarts-map.js"></script>
     <script type="text/javascript">
           require.config({
          paths:{ 
                  echarts:'./js/echarts',
                  'echarts/chart/bar' : '${basePath}/js/echarts-map',
                  'echarts/chart/line': '${basePath}/js/echarts-map',
                  'echarts/chart/map' : '${basePath}/js/echarts-map'
  }
});

    // Step:4 动态加载echarts然后在回调函数中开始使用,注意保持按需加载结构定义图表路径
    require(
      [
      'echarts',
      'echarts/chart/bar',
      'echarts/chart/line',
      'echarts/chart/map'
     ],
      
     function (ec) {
         // 基于准备好的dom,初始化echarts图表
         var myChart = ec.init(document.getElementById('main')); 
         var myid=ec.init(document.getElementById('yulunList'));
         
         $.getJSON( "${basePath}charts/getMap.html", function( data ) {
          myChart.setOption(data);
	   });
	   
	     $.getJSON( "${basePath}charts/gettest.html", function( data ) {
          myid.setOption(data);
	   });
   });

</script>
 </body>

 

如果想让地图做2级页面的跳转,echarts有提供各种接口,例如地图:

var ecConfig = require('echarts/config');
         
         myChart.on(ecConfig.EVENT.MAP_SELECTED, function(param){
             var mt = "";
             // 全国选择时指定到选中的省份
             var selected = param.selected;
             for (var i in selected) {
                 if (selected[i]) {
                     mt = i;
                     var da=option.series[0].data;
                     for(var i=0;i<da.length;i++){
                        if(mt==da[i].name){
                           alert(da[i].value);
                           //这里可以写action,ajax都可以
                           window.open(da[i].url);
                           break;
                        }
                     }
                     break;
                  }
              }
         });

 下面在讲个http://echarts.baidu.com/doc/example/line1.html 这个实例

@Action(value="stra", results={
            @Result(name="success",type="json", params = {
                    "root","chartsJson"
            })})
    public String stra(){
        SimpleDateFormat siFormat=new SimpleDateFormat("yyyy/MM/dd");//获取日期合适
          Option option=new GsonOption();
           option.title().text("关键词文章统计");
           option.tooltip().trigger(Trigger.axis);
           option.legend().data("银行","好");
           ValueAxis axis = new ValueAxis();
           Calendar calendar=Calendar.getInstance();
           calendar.setTime(new Date());//传入当前时间
           List<String> list=new ArrayList<String>();
           calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)-7);
           for(int i=0;i<6;i++){
                calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)+1);
                list.add(siFormat.format(calendar.getTime()));
            }
           axis.type(AxisType.category).boundaryGap(false).data(list.toArray());//把前6天的数据传进去
           option.xAxis(axis);
           CategoryAxis yaxis = new CategoryAxis();
           yaxis.type(AxisType.value);
           option.yAxis(yaxis);
           String[] stri={"银行","好"};
           MarkPoint mp = new MarkPoint() ;
           mp.data(new Data().type(MarkType.max).name("最大值"),
                   new Data().type(MarkType.min).name("最小值")) ;
           Line line;
           for(int i=0;i<stri.length;i++) {
             line = new Line() ;
             line.name(stri[i]).type(SeriesType.line).data(Math.round(Math.random()*1000),Math.round(Math.random()*1000),Math.round(Math.random()*1000),Math.round(Math.random()*1000),Math.round(Math.random()*1000),Math.round(Math.random()*1000)).markPoint(mp);
             option.series(line);
           }
           chartsJson=JSONObject.fromObject(option.toString());
        return SUCCESS;
    }


这个里面我主要讲的是SimpleDateFormat和Calendar用法,如果想要获取当前分钟的秒数,5秒是一个间隔

//        List<String> list=new ArrayList<String>();
        SimpleDateFormat siFormat=new SimpleDateFormat("mm:ss");
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.SECOND , calendar.get(Calendar.SECOND )-30);
        for(int i=0;i<6;i++){
            calendar.set(Calendar.SECOND , calendar.get(Calendar.SECOND )+5);
//            list.add(siFormat.format(calendar.getTime()));
            System.out.println(siFormat.format(calendar.getTime()));
        }

出来的结果是:09:05  09:10  09:15  09:20  09:25  09:30

 

posted @ 2014-10-28 11:10  heart..  阅读(1526)  评论(0编辑  收藏  举报