天天看點

用Echart建立簡單的折線圖

<a href="https://s3.51cto.com/wyfs02/M01/8C/CE/wKiom1h4kSSAaDlZAACgg0MpYLM705.png-wh_500x0-wm_3-wmp_4-s_4264135875.png" target="_blank"></a>

&lt;%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%&gt;

&lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%&gt; 

&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;

&lt;html&gt;

&lt;head&gt;

&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;

&lt;title&gt;機組耗電量統計圖&lt;/title&gt;

&lt;link rel="stylesheet" href="${path }/public/layui/css/layui.css"&gt;

&lt;link rel="stylesheet" href="${path }/public/css/style.css"&gt;

&lt;script type="text/javascript" src="${path }/public/layui/layui.js"&gt;&lt;/script&gt;

&lt;script src="${path }/public/layui/lay/lib/jquery.js"&gt;&lt;/script&gt;

&lt;script src="${path }/public/layui/lay/dest/layui.all.js"&gt;&lt;/script&gt;

&lt;script src="${path }/public/js/jquery-1.4.4.min.js"&gt;&lt;/script&gt;

&lt;script&gt;

layui.use('element', function() {

var $ = layui.jquery, element = layui.element(); //Tab的切換功能,切換事件監聽等,需要依賴element子產品

//觸發事件          

var active = {

tabAdd : function() {

//新增一個Tab項

element.tabAdd('demo', {

title : '新選項' + (Math.random() * 1000 | 0) //用于示範

,

content : '内容' + (Math.random() * 1000 | 0)

})

},

tabDelete : function() {

//删除指定Tab項

element.tabDelete('demo', 2); //删除第3項(注意序号是從0開始計算)

tabChange : function() {

//切換到指定Tab項

element.tabChange('demo', 1); //切換到第2項(注意序号是從0開始計算)

}

};

$('.site-demo-active').on('click', function() {

var type = $(this).data('type');

active[type] ? active[type].call(this) : '';

});

&lt;/script&gt;

&lt;/head&gt; 

&lt;body&gt;

&lt;div class="layui-tab layui-tab-card"&gt;

&lt;ul class="layui-tab-title"&gt;

&lt;li id="power_day"&gt;日&lt;/li&gt;

&lt;li id="power_month"&gt;月&lt;/li&gt;

&lt;li id="power_year"&gt;年&lt;/li&gt;

&lt;/ul&gt;

&lt;div class="layui-tab-content" style="height: 350px;"&gt;

    &lt;div class="layui-tab-item layui-show"&gt;

         &lt;div id="mainone" style="height:380px"&gt;&lt;/div&gt;

    &lt;/div&gt;

    &lt;div class="layui-tab-item layui-show"&gt;     

&lt;div id="maintwo" style="height:380px"&gt;&lt;/div&gt;

&lt;/div&gt;

&lt;div id="mainthree" style="height:380px"&gt;&lt;/div&gt;

&lt;/body&gt;

&lt;!-- ECharts單檔案引入 --&gt;

&lt;script src="${path }/public/js/echarts.js"&gt;&lt;/script&gt;

&lt;script type="text/javascript"&gt;

// 路徑配置

require.config({

paths : {

echarts : 'http://echarts.baidu.com/build/dist'

// 使用

require([ 'echarts', 'echarts/chart/line' // 使用柱狀圖就加載bar子產品,按需加載 (需修改為相應的圖形名稱)

], function(ec) {

// 基于準備好的dom,初始化echarts圖表

var myChart = ec.init(document.getElementById('mainone'));

   var myChartMonth = ec.init(document.getElementById('maintwo')); 

var myChartYear = ec.init(document.getElementById('mainthree'));

loadEchartPower(myChart,1);

//日耗電量

var dayObj = document.getElementById("power_day");

dayObj.addEventListener("click", function(){

}, true);

//月耗電

var monthObj = document.getElementById("power_month");

monthObj.addEventListener("click", function(){

loadEchartPower(myChartMonth,2);

}, true); 

//年耗電

var yearObj = document.getElementById("power_year");

yearObj.addEventListener("click", function(){

loadEchartPower(myChartYear,3);

//機組及蒸發器功率

function loadEchartPower(myChart, type){

var index = layer.load(2, {shade: false},{time: 5*1000}); //0代表加載的風格,支援0-2   添加加載層

$.ajax({

url:path+'/chart/aircrewTmep',

dataType:'json',

type:'post',

data:{coding:'${coding}',type:type},

success:function(data){

//console.log(JSON.stringify(data.series));

//console.log(data.legend);

layer.close(index); //關閉加載層

/*

var legendArr = ['蒸發器1','蒸發器2','蒸發器3','機組1'];

var seriesArr = [{"name":"蒸發器1","type":"line","stack":null,

"data":["0.5","1.00","1.20","1.00","2.50","1.50","4.00","2.50","3.00","1.00","2.00","1.00","2.30","4.00"],"smooth":false},

{"name":"蒸發器2","type":"line","stack":null,

"data":["1.00","1.2","1.5","1.8","2.0","1.5","1.2","2.2","2.3","1.5","2.5","2.8","3.0","3.5"],"smooth":false},

{"name":"蒸發器3","type":"line","stack":null,

"data":["1.2","1.5","1.8","2.0","1.8","1.5","2.2","2.5","2.7","2.0","1.9","2.63","2.8","3.7"],"smooth":false},

{"name":"機組1","type":"line","stack":null,

"data":["2.0","1.2","1.5","1.8","2.1","1.6","1.3","1.8","1.4","1.5","1.6","2.3","3.5","4.0"],"smooth":false}];

*/

option = {

title : {

text : '機組耗電量統計圖',

subtext : '時間/耗電量'

tooltip : {

trigger : 'axis'

legend : {

data : data.legend

                    toolbox: {

                        show : true,

                        feature : {

                            mark : {show: true},

                            dataView : {show: true, readOnly: false},

                            magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},

                            restore : {show: true},

                            saveAsImage : {show: true}

                        }

                    },

calculable : true,

xAxis : [ {

type : 'category',

boundaryGap : false,

data : data.time

} ],

yAxis : [ {

type : 'value'

series : data.series,

// 為echarts對象加載資料

myChart.setOption(option);

&lt;/html&gt;

&lt;!-----------------------------JAVA背景代碼-----------------------------------------&gt;

@Controller

@RequestMapping("/chart")

public class ChartCtrl {

@Autowired

private ChartService chartService;

/**

 * 機組耗電量

 */

@RequestMapping("/aircrewTmep")

@ResponseBody

public Map&lt;String, Object&gt; aircrewTmep(HttpSession session,HttpServletRequest req){

HashMap&lt;String, Object&gt; rlt = new HashMap&lt;&gt;();

try {

Object identityCode = session.getAttribute("identity_code");

if(identityCode==null||"".equals(identityCode)){

return null;

String type = req.getParameter("type");

HashMap&lt;String, String&gt; map = new HashMap&lt;&gt;();

map.put("identity_code", identityCode.toString());

map.put("coding", req.getParameter("coding"));

rlt=chartService.aircrewTmep(map, type);

} catch (Exception e) {

e.printStackTrace();

return rlt;

@Service

public class ChartService {

public HashMap&lt;String, Object&gt; aircrewTmep(HashMap&lt;String, String&gt; map,String type){

List&lt;ChactSeriesVO&gt; chartserieslist = new ArrayList&lt;&gt;();

List&lt;String&gt; legendlist = new ArrayList&lt;&gt;();

String json = null;

String[] timeArr = null;

if(1==Integer.parseInt(type)){ //日

map.put("day", DateTools.createDate());

json = HttpClientUtil.httpPost("http://localhost:8080/test/app/running/day/", map, "utf-8");

}else if(2==Integer.parseInt(type)){ //月

map.put("day", DateTools.yearMonth());

json = HttpClientUtil.httpPost("http://localhost:8080/test/app/running/month/", map, "utf-8");

}else{ //年

map.put("day", DateTools.nowYear());

json = HttpClientUtil.httpPost("http://localhost:8080/test/app/running/year/", map, "utf-8");

System.out.println("---json---"+json);

if(json != null){

ObjectMapper mapper = new ObjectMapper();

JsonNode tree = mapper.readTree(json);

JsonNode evaporatorList = tree.findValue("data").findPath("evaporator");

for (int i = 0; i &lt; evaporatorList.size(); i++) {

JsonNode chart = evaporatorList.get(i);

JsonNode evaplist = chart.findPath("power");

ChactSeriesVO aevo = new ChactSeriesVO();

aevo.setName(chart.get("title").asText());

aevo.setType("line");

aevo.setSmooth(false);

aevo.setData(tempArr(evaplist));

chartserieslist.add(aevo);

legendlist.add(chart.get("title").asText());

JsonNode aircrewlist = tree.findValue("data").findValue("aircrew").findPath("power");

ChactSeriesVO tempaevo = new ChactSeriesVO();

tempaevo.setName(tree.findValue("data").findValue("aircrew").findValue("title").asText());

tempaevo.setType("line");

tempaevo.setSmooth(false);

tempaevo.setData(tempArr(aircrewlist));

chartserieslist.add(tempaevo);

legendlist.add(tree.findValue("data").findValue("aircrew").findValue("title").asText());

JsonNode timelist = tree.findValue("data").findPath("time");

timeArr = new String[timelist.size()];

for (int m = 0; m &lt; timelist.size(); m++) {

String strtime = DateTools.stampToDate(timelist.get(m).asText());

if(1==Integer.parseInt(type)){

timeArr[m] = DateTools.strToHour(strtime);

}else if(2==Integer.parseInt(type)){

timeArr[m] = DateTools.strToDate(strtime);

}else{

timeArr[m] = DateTools.strToMonth(strtime);

//System.out.println("---evaporatorList--"+evaporatorList);

rlt.put("time", timeArr);

rlt.put("series", chartserieslist);

rlt.put("legend", legendlist);

//字元串數組指派

public String[] tempArr(JsonNode templist){

String[] powerarr = new String[templist.size()];

for (int i = 0; i &lt; templist.size(); i++) {

powerarr[i] = new String(templist.get(i).asText());

return powerarr;

/*****************----series對應的實體類----固定字段---友善頁面取值-----***********************/

package com.shangyukeji.icoolcloud.vo;

public class ChactSeriesVO {

private String name;

private String type;

private String stack;

private String[] data;

private boolean smooth;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getType() {

return type;

public void setType(String type) {

this.type = type;

public String getStack() {

return stack;

public void setStack(String stack) {

this.stack = stack;

public String[] getData() {

return data;

public void setData(String[] data) {

this.data = data;

public boolean isSmooth() {

return smooth;

public void setSmooth(boolean smooth) {

this.smooth = smooth;

本文轉自 沉澱人生 51CTO部落格,原文連結:http://blog.51cto.com/825272560/1891822