echarts-springmvc+echarts實現圖表

springmvc+echarts實現圖表


效果圖:

兩種方法實現的效果都一樣,不過針對此圖的話,感覺方法2更好。


Echarts:參照的例子:  http://echarts.baidu.com/doc/example/radar1.html


下面只是關鍵代碼:具體看源碼

該項目源碼下載:http://download.csdn.net/detail/u013147600/9071341

方法1.直接把所需數據傳到jsp頁面中的js中;

controller類:

/**
	 * @param request
	 * @return
	 * 在前端js實現圖表
	 */
	@RequestMapping("/showRadio")
	public ModelAndView showRadio(HttpServletRequest request)
	{
		
	
		List<AllocatedBudget> list = service.addInfo();
		
		
		String strContext =JSON.toJSONString(list);
		System.out.println(strContext);
		
		request.setAttribute("strContext",strContext);
	
		
		return new ModelAndView("/radio1");
	}

jsp頁面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
request.setAttribute("home", path);
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>雷達圖</title>
  
  </head>
  
  <body>
  		<h2>雷達圖</h2>
  	
  	<div id="myRadio"  style="height:400px"></div>
  	
  	
  	<script type="text/javascript" src="${home }/res/js/echarts.js"></script>
  <script type="text/javascript" src="${home }/res/js/macarons.js"></script>
  <script type="text/javascript">
  	var home ="${home}";
  	
  	//獲取到的數據
  	var context =eval('${strContext}');
  	
  	//名稱數組
  	var nameArray = new Array();
  	//數據數組
  	var dataArray= new Array();
  	
  	
  	//將數據進行處理
  	for(var i=0;i<context.length;i++)
  	{	
  		nameArray.push(context[i].planName);
  		
  		//二維數組- 保存數據
  		dataArray[i]= new Array();
  		dataArray[i].push(context[i].sales);
  		
  	 	dataArray[i].push(context[i].administration);
  		dataArray[i].push(context[i].informationTechology);
  		dataArray[i].push(context[i].customerSupport);
  		dataArray[i].push(context[i].development);
  		dataArray[i].push(context[i].marketing); 
  		
  	}  
  	
  	require.config(
  	{
  		paths:{
  		echarts:'res/js'
  		}
  	});
  	require(
  		[
  		'echarts',
  		'echarts/chart/radar',
  		'echarts/chart/line'
  		]
  		, function(ec)
  		{
  			var myChart =ec.init(document.getElementById("myRadio"));
  			
  			
  			option = {
			    title : {
			        text: '預算 vs 開銷 vs我的開銷(Budget vs spending)',
			        subtext: '純屬虛構'
			    },
			    tooltip : {
			        trigger: 'axis'
			    },
			    legend: {
			        orient : 'vertical',
			        x : 'right',
			        y : 'bottom',
			        data:nameArray//['預算分配(Allocated Budget)','實際開銷(Actual Spending)']
			    },
			    toolbox: {
			        show : true,
			        feature : {
			            mark : {show: true},
			            dataView : {show: true, readOnly: false},
			            restore : {show: true},
			            saveAsImage : {show: true}
			        }
			    },
			    polar : [
			       {
			           indicator : 			           
			           [			       
			               { text: '銷售(sales)', max: 6000},
			               { text: '管理(Administration)', max: 16000},
			               { text: '信息技術(Information Techology)', max: 30000},
			               { text: '客服(Customer Support)', max: 38000},
			               { text: '研發(Development)', max: 52000},
			               { text: '市場(Marketing)', max: 25000}  
			            ]
			        }
			    ],
			    calculable : true,
			    series : [
			        {
			            name: '預算 vs 開銷(Budget vs spending)',
			            type: 'radar',
			            data : [			           
			            {
			            	value:dataArray[0],
			            	name:nameArray[0]
			            } ,
			            {
			            	value:dataArray[1],
			            	name:nameArray[1]
			            },
			            {
			            	value:dataArray[2],
			            	name:nameArray[2]
			            }
			            ]
			            
			        }
			    ]
			};
			
			
			myChart.setOption(option);
  		}
  	
  	);
  	
  	
  	
  </script>
  	
  <script type="text/javascript" src="${home }/res/js/jquery.1.7.2.min.js"></script>
   <script type="text/javascript" src="${home }/res/js/jquery-1.11.3.min.js"></script>
  </body>
</html>




方法2.在類中生成類似js代碼,轉換成JSON字符串後傳入到jsp頁面中

關鍵jar包:ECharts-2.2.6.jar 

下載及介紹地址:http://git.oschina.net/free/ECharts#git-readme (根據百度Echarts的一個開源項目,感謝作者)

RadarServiceImpl.java

package com.echarts.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.echarts.dao.RadarDao;
import com.echarts.entity.AllocatedBudget;
import com.echarts.service.RadarService;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.Polar;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.code.X;
import com.github.abel533.echarts.code.Y;
import com.github.abel533.echarts.data.Data;
import com.github.abel533.echarts.feature.DataView;
import com.github.abel533.echarts.feature.Mark;
import com.github.abel533.echarts.feature.Restore;
import com.github.abel533.echarts.feature.SaveAsImage;
import com.github.abel533.echarts.json.FsonOption;
import com.github.abel533.echarts.series.Radar;

/**
 * @author lyx
 *	
 * 2015-9-1上午9:04:04
 *
 *com.echarts.service.impl.RadarServiceImpl
 *
 */

@Service("RadarService")
public class RadarServiceImpl implements RadarService{

	@Autowired
	private RadarDao dao;
	
	public List<AllocatedBudget> addInfo() {
		// TODO Auto-generated method stub
	
		
		return dao.addInfo();
	}

	public FsonOption radarOption() {
		//獲得數據
		List<AllocatedBudget> list = dao.addInfo();
		
		//option設置	
		
		FsonOption option =new FsonOption();
		
        option.title("預算 vs 開銷 vs 我的開銷(Budget vs spending)", "純屬虛構");
        
        option.tooltip(Trigger.axis);
        
        //圖例
        option.legend().orient(Orient.vertical).x(X.right).y(Y.bottom);//.data("預算分配(Allocated Budget)","實際開銷(Actual Spending)","我的開銷");
        
        //圖例說明
    	for (AllocatedBudget alloc: list) {
    		option.legend().data().add(alloc.getPlanName());
    			
    		}
    		
        //工具欄
        option.toolbox().show(true).feature(Tool.mark, Tool.dataView, Tool.restore, Tool.saveAsImage);
        option.calculable(true);

        //極座標
        Polar polar = new Polar();
        polar.indicator(new Data().text("銷售(sales)").max(6000),
                new Data().text("管理(Administration)").max(16000),
                new Data().text("信息技術(Information Techology)").max(30000),
                new Data().text("客服(Customer Support)").max(38000),
                new Data().text("研發(Development)").max(52000),
                new Data().text("市場(Marketing)").max(25000));
        option.polar(polar);
        
        //雷達圖
        Radar radar = new Radar("預算 vs 開銷(Budget vs spending)");
        
        //雷達圖數據
    	for (AllocatedBudget alloc: list) {
	<span style="white-space:pre">	</span>radar.data(new Data().name(alloc.getPlanName().toString()).value(alloc.getSales(),alloc.getAdministration(),alloc.getInformationTechology(),alloc.getCustomerSupport(),alloc.getDevelopment(),alloc.getMarketing()));
		}
        
       
		option.series(radar);
		
		
		System.out.println(option);
		return option;
	}

}

controller方法:

/**
	 * @param request
	 * @return
	 * 在dao層的類中實現Option
	 */
	@RequestMapping("/radarOption")
	public ModelAndView radarOption(HttpServletRequest request)
	{
		
		
		FsonOption option = service.radarOption();
		
		request.setAttribute("option", option);
		
		
		return new ModelAndView("/rect");
	}

jsp頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
request.setAttribute("home", path);
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>雷達圖</title>
  
  </head>
  
  <body>
  		<h2>雷達圖</h2>
  	
  	<div id="myRadio"  style="height:400px"></div>
  	
  	
  	<script type="text/javascript" src="${home }/res/js/echarts.js"></script>
  <script type="text/javascript" src="${home }/res/js/macarons.js"></script>
  <script type="text/javascript">
  	var home ="${home}";
  	
  	
  	
  	
  	
  	require.config({
	  	paths:
	  	{
	  		echarts:'res/js'
	  	}
  	});
  	
  	
  	var option = ${option};
  	require(
  	[
  		'echarts',
  		'echarts/chart/radar',
  		'echarts/chart/line'
  	],
  	function(ec)
  	{
  		var myChart =ec.init(document.getElementById("myRadio"));
  		
  		myChart.setOption(option);
  	}
  	);
  	
  </script>
  	
  <script type="text/javascript" src="${home }/res/js/jquery.1.7.2.min.js"></script>
   <script type="text/javascript" src="${home }/res/js/jquery-1.11.3.min.js"></script>
  </body>
</html>

運行成功的後頁面源碼:

運行後的js:

 var home ="/springEcharts001";
   
   require.config({
    paths:
    {
     echarts:'res/js'
    }
   });
   
   var option = {"calculable":true,

 "legend":{"data":["預算分配","實際開銷","我的開銷"],"orient":"vertical","x":"right","y":"bottom"},

 "polar":[{"indicator":[{"max":6000,"text":"銷售(sales)"},{"max":16000,"text":"管理(Administration)"},
 {"max":30000,"text":"信息技術(Information Techology)"},{"max":38000,"text":"客服(Customer Support)"},
 {"max":52000,"text":"研發(Development)"},{"max":25000,"text":"市場(Marketing)"}]}],
 
 "series":[{"data":[{"name":"預算分配","value":[4300,10000,28000,35000,50000,19000]},
 {"name":"實際開銷","value":[5000,14000,28000,31000,42000,21000]},
 {"name":"我的開銷","value":[1000,4000,8000,8000,20000,10000]}],
 "name":"預算 vs 開銷(Budget vs spending)","type":"radar"}],
 
 "title":{"subtext":"純屬虛構","text":"預算 vs 開銷 vs 我的開銷(Budget vs spending)"},
 
 "toolbox":{"feature":{"mark":{"lineStyle":{"color":"#1e90ff","type":"dashed","width":2},"show":true,
 "title":{"mark":"輔助線開關","markClear":"清空輔助線","markUndo":"刪除輔助線"}},
 "dataView":{"lang":["數據視圖","關閉","刷新"],"readOnly":false,"show":true,"title":"數據視圖"},
 "restore":{"show":true,"title":"還原"},"saveAsImage":{"lang":["點擊保存"],"show":true,"title":"保存爲圖片","type":"png"}},"show":true},
 
 "tooltip":{"trigger":"axis"}};
   require(
   [
    'echarts',
    'echarts/chart/radar',
    'echarts/chart/line'
   ],
   function(ec)
   {
    var myChart =ec.init(document.getElementById("myRadio"));
   
    myChart.setOption(option);
   }
   );



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章