Echarts-echart和springMVC實現堆棧圖(讀取JSON檔案資料),

來源:互聯網
上載者:User

Echarts-echart和springMVC實現堆棧圖(讀取JSON檔案資料),

這篇echarts的堆棧圖主要是根據這篇D3.js堆棧圖(http://blog.csdn.net/u013147600/article/details/46770415 )實現的。




1.JSON檔案資料:

{"name":"某市2005-1010年利潤情況","product":[{ "name": "PC" ,   "sales": [{ "year":"2005", "profit": 3000 },{ "year":"2006", "profit": 1300 },{ "year":"2007", "profit": 3700 },{ "year":"2008", "profit": 4900 },{ "year":"2009", "profit": 700 },{ "year":"2010", "profit": 700 }] },{ "name": "SmartPhone" ,   "sales": [{ "year":"2005", "profit": 2000 },{ "year":"2006", "profit": 4000 },{ "year":"2007", "profit": 1810 },{ "year":"2008", "profit": 6540 },{ "year":"2009", "profit": 2820 },{ "year":"2010", "profit": 1000 }] },{ "name": "Software" ,   "sales": [{ "year":"2005", "profit": 1100 },{ "year":"2006", "profit": 1700 },{ "year":"2007", "profit": 1680 },{ "year":"2008", "profit": 4000 },{ "year":"2009", "profit": 4900 },{ "year":"2010", "profit": 700 }] }]}


2.根據JSON檔案建立的執行個體類

Domain.java

package com.entity;/** * @author lyx * * 2015-7-7上午11:09:19 * *springechart.com.entity.Product */public class Domain {private String name;private Product product;public String getName() {return name;}public void setName(String name) {this.name = name;}public Product getProduct() {return product;}public void setProduct(Product product) {this.product = product;}}

Product.java
package com.entity;/** * @author lyx * * 2015-7-7上午11:10:11 * *springechart.com.entity.Sales */public class Product {private String name;private Sales sale;public String getName() {return name;}public void setName(String name) {this.name = name;}public Sales getSale() {return sale;}public void setSale(Sales sale) {this.sale = sale;}}
Sales.java

package com.entity;/** * @author lyx * * 2015-7-7下午2:10:54 * *springechart.com.entity.Profit */public class Sales {private String year;private int profit;public String getYear() {return year;}public void setYear(String year) {this.year = year;}public int getProfit() {return profit;}public void setProfit(int profit) {this.profit = profit;}}

2.服務層代碼:

EchartsT.java

package com.service;import java.io.File;import java.io.FileNotFoundException;import java.lang.reflect.Array;import java.util.ArrayList;import java.util.List;import java.util.Scanner;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;import com.entity.China;import com.entity.Domain;import com.entity.Sales;import com.entity.Provinces;import com.entity.Product;import com.github.abel533.echarts.Label;import com.github.abel533.echarts.Option;import com.github.abel533.echarts.Title;import com.github.abel533.echarts.axis.CategoryAxis;import com.github.abel533.echarts.axis.ValueAxis;import com.github.abel533.echarts.code.LineType;import com.github.abel533.echarts.code.Magic;import com.github.abel533.echarts.code.MarkType;import com.github.abel533.echarts.code.Orient;import com.github.abel533.echarts.code.PointerType;import com.github.abel533.echarts.code.SelectedMode;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.data.PointData;import com.github.abel533.echarts.feature.MagicType;import com.github.abel533.echarts.series.Bar;import com.github.abel533.echarts.series.Funnel;import com.github.abel533.echarts.series.Line;import com.github.abel533.echarts.series.Map;import com.github.abel533.echarts.series.MapLocation;import com.github.abel533.echarts.series.Pie;import com.github.abel533.echarts.style.ItemStyle;import com.github.abel533.echarts.style.LineStyle;import com.google.gson.JsonArray;/** * @author lyx * * 2015-6-12下午1,34,50 * *springechart.com.service.EchartsT */public class EchartsT {       /**     * 讀取json檔案     */    public String jsonRead(String fullFileName)    {            File file = new File(fullFileName);        Scanner scanner = null;        StringBuilder buffer = new StringBuilder();        try {            scanner = new Scanner(file, "utf-8");            while (scanner.hasNextLine()) {                buffer.append(scanner.nextLine());            }         } catch (FileNotFoundException e) {            // TODO Auto-generated catch block          System.out.println(e);        } finally {            if (scanner != null) {                scanner.close();            }        }         //返回字串        return buffer.toString();    }            /**     * @return     * 堆棧圖     */    public Option stackYear()    {    //Json檔案所在的路徑    String fullFileName="E:/java/java code/Project/springechart/WebRoot/year.json";        //調用讀取檔案函數    String data = jsonRead(fullFileName);        //把字串轉換成Json對象    JSONObject obj =JSON.parseObject(data);    //提取json檔案裡面"product"對應的數組並儲存為Json數組    JSONArray proArr = obj.getJSONArray("product");        //擷取用例說明名稱    String legendName[] = new String[proArr.size()];    for (int i = 0; i < proArr.size(); i++) {    //根據"name"獲得JOSN數組中的名稱    legendName[i]=proArr.getJSONObject(i).getString("name");}        //PC資料    //根據"sales"獲得JOSN數組    JSONArray pcArr =JSON.parseArray(proArr.getJSONObject(0).getString("sales").toString());    //把JSON數組儲存為List列表    List<Sales> pcList = JSON.parseArray(pcArr.toString(), Sales.class);    //計算資料行表大小    int length =pcList.size();    //儲存 年份數組    String[] pcYear =new String[length];    //儲存 利潤數組    int[] pcProfit = new int[length];    //獲得資料 儲存在數組中    for (int i = 0; i <length; i++) {pcYear[i]=pcList.get(i).getYear();pcProfit[i]=pcList.get(i).getProfit();}        //SmartPhone資料    JSONArray spArr =JSON.parseArray(proArr.getJSONObject(1).getString("sales").toString());    List<Sales> spList =JSON.parseArray(spArr.toString(), Sales.class);        String[] spYear =new String[length];    int[] spProfit = new int[length];        for (int i = 0; i <length; i++) {spYear[i]=spList.get(i).getYear();spProfit[i]=spList.get(i).getProfit();}        //Software資料    JSONArray swArr = JSON.parseArray(proArr.getJSONObject(2).getString("sales").toString());    List<Sales> swList =JSON.parseArray(swArr.toString(), Sales.class);        String[] swYear =new String[length];    int[] swProfit = new int[length];        for (int i = 0; i <length; i++) {swYear[i]=swList.get(i).getYear();swProfit[i]=swList.get(i).getProfit();}        //定義Option對象    Option option = new Option();      //標題列    option.title(obj.getString("name"),"純屬虛構");    option.title().x(X.center);    //提示框    option.tooltip().trigger(Trigger.axis);    option.tooltip().axisPointer().type(PointerType.shadow);    //工具列    option.toolbox().show(true).orient(Orient.vertical).x(X.right).y(Y.center).feature(Tool.mark,Tool.dataView,Tool.dataZoom,Tool.restore,Tool.saveAsImage,new MagicType(Magic.bar,Magic.line,    Magic.stack,Magic.tiled));    //用例說明    option.legend().data(legendName).orient(Orient.horizontal).x(X.right);    //可計算    option.calculable(true);     //x軸-類目軸    option.xAxis(new CategoryAxis().data(    pcYear        ));    //y軸 - 值軸    option.yAxis(new ValueAxis());            //PC柱狀體    Bar pcBar = new Bar(legendName[0]).stack("PC");        /*bar.data(provinceProfit);*/ //返回的js代碼中 data資料比需要的資料會多一對中括弧,取不到資料,導致圖形不能正常顯示    //這裡通過add()逐個添加資料    for (int i = 0; i < length; i++) {pcBar.data().add(pcProfit[i]);}        //smartPhone柱狀體    Bar spBar = new Bar(legendName[1]).stack("SmartPhone");    for (int i = 0; i < length; i++) {    spBar.data().add(spProfit[i]);}        //software柱狀體    Bar swBar = new Bar(legendName[2]).stack("Software");    for (int i = 0; i < length; i++) {    swBar.data().add(swProfit[i]);}        //設定系列series    option.series(pcBar,spBar,swBar);    return option;        }       }


3.控制層代碼:

echartsContr.java

package com.controller;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.alibaba.fastjson.JSON;import com.github.abel533.echarts.Option;import com.service.EchartsT;/** * @author lyx * * 2015-6-12下午1:36:51 * *springechart.com.controller.echartsContr */@Controller@RequestMapping("/echarts")public class echartsContr {EchartsT ech = new EchartsT();/** * @param res * @return * 堆棧圖 */@RequestMapping("stackYear")public String stackYear(HttpServletRequest res){//調用服務層的函數並儲存傳回值Option option=ech.stackYear();//通過json裝換成字串String opt =JSON.toJSONString(option);//將對象傳入到jsp頁面res.setAttribute("option", opt);return "/ec";}}

4.jsp頁面代碼:

ec.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <!DOCTYPE html><head>    <meta charset="utf-8">    <title>ECharts</title>  <script type="text/javascript" src="../js/jquery-1.11.3.min.js"></script>  </head><body>    <!-- 為ECharts準備一個具備大小(寬高)的Dom -->    <div id="main" style="height:400px"></div>    <!-- ECharts單檔案引入 -->    <!--  <script src="http://echarts.baidu.com/build/dist/echarts.js"></script>  -->   <script type="text/javascript" src="../js/echarts.js"></script>       <!-- <script type="text/javascript" src="js/echarts-all.js"></script> -->    <script type="text/javascript">    //路徑配置    require.config({    paths:{     echarts: '../js'    }    });      //獲得後台傳過來的JSON資料    var opt =${option};    //設定主要樣式    require(    [    'echarts',    'echarts/chart/bar',    'echarts/chart/line',    'echarts/chart/pie',    'echarts/chart/map',    'echarts/chart/funnel'    ],    function(ec){     //初始化echart對象    var chart =ec.init(document.getElementById('main'));   chart.setOption(opt);      });       </script></body></html>

5.運行成功後的頁面源碼:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <!DOCTYPE html><head>    <meta charset="utf-8">    <title>ECharts</title>  <script type="text/javascript" src="../js/jquery-1.11.3.min.js"></script>  </head><body>    <!-- 為ECharts準備一個具備大小(寬高)的Dom -->    <div id="main" style="height:400px"></div>    <!-- ECharts單檔案引入 -->    <!--  <script src="http://echarts.baidu.com/build/dist/echarts.js"></script>  -->   <script type="text/javascript" src="../js/echarts.js"></script>       <!-- <script type="text/javascript" src="js/echarts-all.js"></script> -->    <script type="text/javascript">    //路徑配置    require.config({    paths:{     echarts: '../js'    }    });      //獲得後台傳過來的JSON資料    var opt ={"calculable":true,"legend":{"data":["PC","SmartPhone","Software"],"orient":"horizontal","x":"right"},"series":[{"data":[3000,1300,3700,4900,700,700],"name":"PC","stack":"PC","type":"bar"},{"data":[2000,4000,1810,6540,2820,1000],"name":"SmartPhone","stack":"SmartPhone","type":"bar"},{"data":[1100,1700,1680,4000,4900,700],"name":"Software","stack":"Software","type":"bar"}],"title":{"subtext":"純屬虛構","text":"某市2005-1010年利潤情況","x":"center"},"toolbox":{"feature":{"mark":{"lineStyle":{"color":"#1e90ff","type":"dashed","width":2},"show":true,"title":{"mark":"輔助線開關","markClear":"清空輔助線","markUndo":"刪除輔助線"}},"dataView":{"lang":["資料檢視","關閉","重新整理"],"readOnly":false,"show":true,"title":"資料檢視"},"dataZoom":{"show":true,"title":{"dataZoom":"地區縮放","dataZoomReset":"地區縮放後退"}},"restore":{"show":true,"title":"還原"},"saveAsImage":{"lang":["點擊儲存"],"show":true,"title":"儲存為圖片","type":"png"},"magicType":{"show":true,"title":{"line":"折線圖切換","stack":"堆積","bar":"直條圖切換","tiled":"平鋪"},"type":["bar","line","stack","tiled"]}},"orient":"vertical","show":true,"x":"right","y":"center"},"tooltip":{"axisPointer":{"type":"shadow"},"trigger":"axis"},"xAxis":[{"data":["2005","2006","2007","2008","2009","2010"],"type":"category"}],"yAxis":[{"type":"value"}]};    //設定主要樣式    require(    [    'echarts',    'echarts/chart/bar',    'echarts/chart/line',    'echarts/chart/pie',    'echarts/chart/map',    'echarts/chart/funnel'    ],    function(ec){     //初始化echart對象    var chart =ec.init(document.getElementById('main'));//ec.init( $("#main"));   chart.setOption(opt);      });                                </script>       </body></html>

參考網站:http://git.oschina.net/free/ECharts

通過上面網站作者所編寫的ECharts-2.2.4.jar ,匯入到我們工程中這樣我們的頁面中的js代碼,就可以現在項目的後台產生,並通過json轉換成字串傳入到頁面中,在jsp頁面接收傳入的json格式的字串,後就可以產生我們設定的圖表了。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.