1. 程式人生 > >百度ECharts圖表展示動態資料

百度ECharts圖表展示動態資料

百度ECharts是個非常強大的圖表工具,引入百度提供的echarts.min.js檔案後,只需從後臺獲取資料便可以圖表的形式展示資料,能夠更直觀的檢視、比較、統計資料。

這裡以一個柱狀圖展示動態資料的小例子講解如何使用百度ECharts。

1.首先引入需要的js檔案:

    <!-- jquery -->
	<script src="https://cdn.bootcss.com/jquery/2.2.3/jquery.min.js"></script>
    <!-- 百度ECharts -->
	<script src="<%=basePath%>js/echarts.min.js"></script>

echarts.min.js自行去百度下載

2.建立columnChart.jsp,(這裡可以直接去百度ECharts下載,有各式各樣的柱狀圖):

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>柱狀圖</title>
    <c:import url="resources.jsp"></c:import>
  </head>
  
  <body>
  	<!--為Echarts準備一個Div放置圖表-->
    <div id="main" style="width:600px;height:400px;"></div>
  </body>
  <script type="text/javascript">
  	$(function () {
			//將echart初始化到div中
            var myChart=echarts.init(document.getElementById("main"));
            var dataAxis = [];
            var data = [];
            var yMax = 500;//y軸最大值
            var dataShadow = [];
            
            for (var i = 0; i < data.length; i++) {
                dataShadow.push(yMax);
            }

            var option = {
                title: {
                    text: '特性示例:漸變色 陰影 點選縮放',
                    subtext: 'Feature Sample: Gradient Color, Shadow, Click Zoom'
                },
                xAxis: {
                    data: dataAxis,
                    axisLabel: {
                        inside: true,
                        textStyle: {
                            color: '#fff'
                        }
                    },
                    axisTick: {
                        show: false
                    },
                    axisLine: {
                        show: false
                    },
                    z: 10
                },
                yAxis: {
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        textStyle: {
                            color: '#999'
                        }
                    }
                },
                dataZoom: [
                    {
                        type: 'inside'
                    }
                ],
                series: [
                    { // For shadow
                        type: 'bar',
                        itemStyle: {
                            normal: {color: 'rgba(0,0,0,0.05)'}
                        },
                        barGap:'-100%',
                        barCategoryGap:'40%',
                        data: dataShadow,
                        animation: false
                    },
                    {
                        type: 'bar',
                        itemStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(
                                    0, 0, 0, 1,
                                    [
                                        {offset: 0, color: '#83bff6'},
                                        {offset: 0.5, color: '#188df0'},
                                        {offset: 1, color: '#188df0'}
                                    ]
                                )
                            },
                            emphasis: {
                                color: new echarts.graphic.LinearGradient(
                                    0, 0, 0, 1,
                                    [
                                        {offset: 0, color: '#2378f7'},
                                        {offset: 0.7, color: '#2378f7'},
                                        {offset: 1, color: '#83bff6'}
                                    ]
                                )
                            }
                        },
                        data: data
                    }
                ]
            };

            var zoomSize = 6;
            myChart.on('click', function (params) {
                console.log(dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)]);
                myChart.dispatchAction({
                    type: 'dataZoom',
                    startValue: dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)],
                    endValue: dataAxis[Math.min(params.dataIndex + zoomSize / 2, data.length - 1)]
                });
            });

            myChart.setOption(option)  ;
        });
  </script>
</html>

因為我的js檔案都是在resources.jsp中引入的,所以這裡在columnChart.jsp中引用resources.jsp就可以了,可以根據自己的習慣引入js檔案,直接複製貼上的小白出了問題自己解決。

另外這個時候是沒有資料的,接下來寫後臺方法傳遞資料給jsp。我這裡的例子是用水果的銷量做展示,後臺程式碼不做贅述,看看就好,這裡最好自己寫,不難。

ProductMapper.xml:

<!-- 檢視所有商品銷量 -->
    <select id="getSales" resultType="com.demo.model.Product">
    	select name,sales from t_product
    </select>

Dao層和Service層省略,其中name是水果名,sales是銷量。

ProductController.java:

/**
	 * 獲得柱狀圖資料
	 * @return
	 */
	@RequestMapping("/getColumnChart")
	@ResponseBody
	public List<Product> getColumnChart(){
		List<Product> list = productService.getSales();
		return list;
	}

最後,回到columnChart.jsp中,寫上ajax方法呼叫剛剛寫的方法,全部程式碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>柱狀圖</title>
    <c:import url="resources.jsp"></c:import>
  </head>
  
  <body>
  	<!--為Echarts準備一個Div放置圖表-->
    <div id="main" style="width:600px;height:400px;"></div>
  </body>
  <script type="text/javascript">
  	function getData(dataAxis,data){
  		$.ajax({
  				async: false,
            	url:"getColumnChart",
            	type:"get",
            	dataType:"json",
            	success:function(list){
            		for(var i =0;i < list.length;i++){
            			dataAxis.push(list[i].name);
            			data.push(list[i].sales);
            		}
            	}
            })
  	}
  	$(function () {
			//將echart初始化到div中
            var myChart=echarts.init(document.getElementById("main"));
            var dataAxis = [];
            var data = [];
            getData(dataAxis,data);
            var yMax = 500;//y軸最大值
            var dataShadow = [];
            
            for (var i = 0; i < data.length; i++) {
                dataShadow.push(yMax);
            }

            var option = {
                title: {
                    text: '特性示例:漸變色 陰影 點選縮放',
                    subtext: 'Feature Sample: Gradient Color, Shadow, Click Zoom'
                },
                xAxis: {
                    data: dataAxis,
                    axisLabel: {
                        inside: true,
                        textStyle: {
                            color: '#fff'
                        }
                    },
                    axisTick: {
                        show: false
                    },
                    axisLine: {
                        show: false
                    },
                    z: 10
                },
                yAxis: {
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        textStyle: {
                            color: '#999'
                        }
                    }
                },
                dataZoom: [
                    {
                        type: 'inside'
                    }
                ],
                series: [
                    { // For shadow
                        type: 'bar',
                        itemStyle: {
                            normal: {color: 'rgba(0,0,0,0.05)'}
                        },
                        barGap:'-100%',
                        barCategoryGap:'40%',
                        data: dataShadow,
                        animation: false
                    },
                    {
                        type: 'bar',
                        itemStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(
                                    0, 0, 0, 1,
                                    [
                                        {offset: 0, color: '#83bff6'},
                                        {offset: 0.5, color: '#188df0'},
                                        {offset: 1, color: '#188df0'}
                                    ]
                                )
                            },
                            emphasis: {
                                color: new echarts.graphic.LinearGradient(
                                    0, 0, 0, 1,
                                    [
                                        {offset: 0, color: '#2378f7'},
                                        {offset: 0.7, color: '#2378f7'},
                                        {offset: 1, color: '#83bff6'}
                                    ]
                                )
                            }
                        },
                        data: data
                    }
                ]
            };

            var zoomSize = 6;
            myChart.on('click', function (params) {
                console.log(dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)]);
                myChart.dispatchAction({
                    type: 'dataZoom',
                    startValue: dataAxis[Math.max(params.dataIndex - zoomSize / 2, 0)],
                    endValue: dataAxis[Math.min(params.dataIndex + zoomSize / 2, data.length - 1)]
                });
            });

            myChart.setOption(option)  ;
        });
  </script>
</html>

加粗特別注意:ajax方法裡一定要寫上async: false。async. 預設是true,即為非同步方式。async設定為:false,請求為同步請求,async設定為:true,則不會等待ajax請求返回的結果,會直接執行ajax後面的語句。如果不加async:false則會導致未等ajax請求返回結果就會執行後面的語句從而導致data無值從而導致圖表沒有資料展示。切記切記!

效果圖: