基于SpringMVC框架使用ECharts3.0实现折线图,柱状图,饼状图,的绘制(上篇)

2017-04-25 19:33

基于SpringMVC框架使用ECharts3.0实现折线图,柱状图,饼状图,的绘制

页面部分

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts柱状图</title>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript" src="../js/echarts.js"></script>
</head>
<body>
    <!-- 为ECharts准备一个具备大小(宽高)的Dom -->
    <div id="main" style="width: 600px;height:400px;"></div>
    <script type="text/javascript">
        $().ready(function() {
            var myChart = echarts.init(document.getElementById('main'));
            //图表显示提示信息
            myChart.showLoading();
            //定义图表options
            var options = {
                color : [ '#3398DB' ],
                title : {
                    text : "通过Ajax获取数据呈现图标示例",
                    subtext : "www.stepday.com",
                    sublink : "http://www.stepday.com/myblog/?Echarts"
                },
                tooltip : {
                    trigger : 'axis'
                },
                legend : {
                    data : []
                },
                toolbox : {
                    show : true,
                    feature : {
                        mark : false
                    }
                },
                calculable : true,
                xAxis : [ {
                    type : 'category',
                    data : []
                } ],
                yAxis : [ {
                    type : 'value',
                    splitArea : {
                        show : true
                    }
                } ],
                series : [ {
                    barWidth : '60%'
                } ]
            };

            //通过Ajax获取数据
            $.ajax({
                type : "post",
                async : false, //同步执行
                url : "showEchartBar.action",
                dataType : "json", //返回数据形式为json
                success : function(result) {
                    if (result) {
                        //将返回的category和series对象赋值给options对象内的category和series
                        //因为xAxis是一个数组 这里需要是xAxis[i]的形式
                        options.xAxis[0].data = result.category;
                        options.series = result.series;
                        options.legend.data = result.legend;

                        myChart.hideLoading();
                        myChart.setOption(options);
                    }
                },
                error : function(errorMsg) {
                    alert("图表请求数据失败啦!");
                }
            });

        });
    </script>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>echarts饼状图</title>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript" src="../js/echarts.js"></script>
</head>
<body>
    <!--定义页面图表容器-->
    <!-- 必须制定容器的大小(height、width) -->
    <div id="main"
        style="height: 400px; border: 1px solid #ccc; padding: 10px;"></div>

    <script type="text/javascript">
        $().ready(function() {
            var myChart = echarts.init(document.getElementById('main'));
            //图表显示提示信息
            myChart.showLoading();
            //定义图表options
            var options = {
                title : {
                    text : '某站点用户访问来源',
                    subtext : '纯属虚构',
                    x : 'center'
                },
                tooltip : {
                    trigger : 'item',
                    formatter : "{a} <br/>{b} : {c} ({d}%)"
                },
                legend : {
                    orient : 'vertical',
                    left : 'left',
                    data : []
                },
                series : [ {
                    name : '访问来源',
                    type : 'pie',
                    data : []
                } ]
            };
            //通过Ajax获取数据
            $.ajax({
                type : "post",
                async : false, //同步执行
                url : "showEchartPie.action",
                dataType : "json", //返回数据形式为json
                success : function(result) {
                    if (result) {
                        options.legend.data = result.legend;

                        //将返回的category和series对象赋值给options对象内的category和series
                        //因为xAxis是一个数组 这里需要是xAxis[i]的形式
                        options.series[0].name = result.series[0].name;
                        options.series[0].type = result.series[0].type;
                        var serisdata = result.series[0].data;
                        
                        //遍历
                        /* var datas = [];
                        for ( var i = 0; i < serisdata.length; i++) {
                            datas.push({
                                name : serisdata[i].name,
                                value : serisdata[i].value
                            });
                        }
                        options.series[0].data = datas; */

                        //jquery遍历
                        var value = [];
                        $.each(serisdata, function(i, p) {
                            value[i] = {
                                'name' : p['name'],
                                'value' : p['value']
                            };
                        });
                        options.series[0]['data'] = value;

                        myChart.hideLoading();
                        myChart.setOption(options);
                    }
                },
                error : function(errorMsg) {
                    alert("图表请求数据失败啦!");
                }
            });

        });
    </script>

</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../js/echarts.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
</head>
<title>echarts折线图</title>
<body>
    <!--定义页面图表容器-->
    <!-- 必须制定容器的大小(height、width) -->
    <div id="main"
        style="height: 400px; border: 1px solid #ccc; padding: 10px;"></div>

    <script type="text/javascript">
        $().ready(
                function() {
            var myChart = echarts.init(document.getElementById('main'));
            //图表显示提示信息
           myChart.showLoading();
            //定义图表options
            var options = {
                title: {
                    text: "通过Ajax获取数据呈现图标示例",
                    subtext: "www.stepday.com",
                    sublink: "http://www.stepday.com/myblog/?Echarts"
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: []
                },
                toolbox: {
                    show: true,
                    feature: {
                        mark: false
                    }
                },
                calculable: true,
                xAxis: [
                    {
                        type: 'category',
                        data: []
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        splitArea: { show: true }
                    }
                ],
                series: []
                };

                    //通过Ajax获取数据
                    $.ajax({
                        type : "post",
                        async : false, //同步执行
                        url : "showEchartLine.action",
                        dataType : "json", //返回数据形式为json
                        success : function(result) {
                            if (result) {
                                //将返回的category和series对象赋值给options对象内的category和series
                                //因为xAxis是一个数组 这里需要是xAxis[i]的形式
                                    options.xAxis[0].data = result.category;
                                    options.series = result.series;
                                    options.legend.data = result.legend;
                                    myChart.hideLoading();
                                    myChart.setOption(options);
                            }
                        },
                        error : function(errorMsg) {
                            alert("图表请求数据失败啦!");
                        }
                    });

                });
    </script>
</body>
</html>

后端java代码

@Controller
@RequestMapping("/echartsJSP")
public class EchartAction {

    @Autowired
    private TotalNumBiz toatlNumBiz;
    @Autowired
    private VisitBiz visitBiz;
    
    
    @RequestMapping("/showEchartLine")
    @ResponseBody
    public EchartData lineData() {
        System.out.println("折线图");
        List<String> category = new ArrayList<String>();
        List<Long> serisData=new ArrayList<Long>();
        List<TotalNum> list = toatlNumBiz.findAll();
        for (TotalNum totalNum : list) {
            category.add(totalNum.getWeek());
            serisData.add(totalNum.getCount());
        }
        List<String> legend = new ArrayList<String>(Arrays.asList(new String[] { "总数比较" }));// 数据分组
        List<Series> series = new ArrayList<Series>();// 纵坐标
        series.add(new Series("总数比较", "line", serisData));
        EchartData data = new EchartData(legend, category, series);
        return data;
    }
    @RequestMapping("/showEchartBar")
    @ResponseBody
    public EchartData BarData() {
        System.out.println("柱状图");
        List<String> category = new ArrayList<String>();
        List<Long> serisData=new ArrayList<Long>();
        List<TotalNum> list = toatlNumBiz.findAll();
        for (TotalNum totalNum : list) {
            category.add(totalNum.getWeek());
            serisData.add(totalNum.getCount());
        }
        List<String> legend = new ArrayList<String>(Arrays.asList(new String[] { "总数比较" }));// 数据分组
        List<Series> series = new ArrayList<Series>();// 纵坐标
        series.add(new Series("总数比较", "bar", serisData));
        EchartData data = new EchartData(legend, category, series);
        return data;
    }
    /**
     * 饼状图
     * @param <T>
     * @return
     */
    @RequestMapping("/showEchartPie")
    @ResponseBody
    public EchartData PieData() {
        List<String> legend = new ArrayList<String>();
        List<Map> serisData=new ArrayList<Map>();
        
        List<Visit> list = visitBiz.findAll();
        for (Visit visit : list) {
            Map map =new HashMap();
            legend.add(visit.getName());
            map.put("value", visit.getValue());
            map.put("name",visit.getName());
            serisData.add(map);
        }
        List<Series> series = new ArrayList<Series>();// 纵坐标
        series.add(new Series("总数比较", "pie",serisData));
        EchartData data = new EchartData(legend,null, series);
        return data;
    }
}

另外使用EchartsData和Series两个类封装数据

public class EchartData {

    public List<String> legend = new ArrayList<String>();// 数据分组
    public List<String> category = new ArrayList<String>();// 横坐标
    public List<Series> series = new ArrayList<Series>();// 纵坐标

    public EchartData(List<String> legendList, List<String> categoryList,
            List<Series> seriesList) {
        super();
        this.legend = legendList;
        this.category = categoryList;
        this.series = seriesList;
    }
}
public class Series<T>{
    public String name;

    public String type;
    public List<T> data;// 这里要用int 不能用String 不然前台显示不正常(特别是在做数学运算的时候)

    public Series(String name, String type, List<T> data) {
        super();
        this.name = name;
        this.type = type;
        this.data = data;
    }

测试使用的实体类及其他部分

public class TotalNum {
    private Integer id;

    private String week;

    private Long count;
public class Visit {
    private Integer id;

    private String name;

    private Integer value;

 

SpringMVC框架下使用jfreechart绘制折线图,柱状图,饼状图

java代码

@Controller
public class CityAction {

    @Autowired
    private CityBiz cityBiz;

    //柱状图
    @RequestMapping(value = "getColumnChart")
    public ModelAndView getColumnChart(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap)
            throws Exception {
        CategoryDataset dataset = getDataSet(cityBiz.findAll());
        JFreeChart chart = ChartFactory.createBarChart3D("用户统计报表(所属单位)", // 主标题的名称
                "所属单位名称", // X轴的标签
                "数量", // Y轴的标签
                dataset, // 图标显示的数据集合
                PlotOrientation.VERTICAL, // 图像的显示形式(水平或者垂直)
                true, // 是否显示子标题
                true, // 是否生成提示的标签
                true); // 是否生成URL链接

        JfreeUtil.setJfreeChart(chart);
        // 6. 将图形转换为图片,传到前台
        String fileName = ServletUtilities.saveChartAsJPEG(chart, 700, 400, null, request.getSession());
        String chartURL = request.getContextPath() + "/chart?filename=" + fileName;
        modelMap.put("chartURLBar", chartURL);
        return new ModelAndView("index", modelMap);
    }

    //饼状图
    @RequestMapping(value = "getColumnpie")
    public ModelAndView getColumnpie(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap)
            throws Exception {
        DefaultPieDataset dataset = getDataSetpie(cityBiz.findAll());

        JFreeChart chart = ChartFactory.createPieChart3D("用户统计报表(所属单位)", // 主标题的名称
                dataset, // 图标显示的数据集合
                true, // 是否显示子标题
                true, // 是否生成提示的标签
                true); // 是否生成URL链接

        JfreeUtil.setJfreePie(chart);

        // 6. 将图形转换为图片,传到前台
        String fileName = ServletUtilities.saveChartAsJPEG(chart, 700, 400, null, request.getSession());
        String chartURL = request.getContextPath() + "/chart?filename=" + fileName;
        modelMap.put("chartURLPie", chartURL);
        return new ModelAndView("index", modelMap);
    }
    
    //折线图
    @RequestMapping(value = "getColumnLine")
    public ModelAndView getColumnLine(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap)
            throws Exception {
        DefaultCategoryDataset dataset = getDataSetLine(cityBiz.findAll());
        
        JFreeChart chart = ChartFactory.createLineChart("用户统计报表(所属单位)", // 主标题的名称
                "所属单位名称", // X轴的标签
                "数量", // Y轴的标签
                dataset, // 图标显示的数据集合
                PlotOrientation.VERTICAL, // 图像的显示形式(水平或者垂直)
                true, // 是否显示子标题
                true, // 是否生成提示的标签
                true); // 是否生成URL链接
        
        JfreeUtil.setJfreeLine(chart);

        
        // 6. 将图形转换为图片,传到前台
        String fileName = ServletUtilities.saveChartAsJPEG(chart, 700, 400, null, request.getSession());
        String chartURL = request.getContextPath() + "/chart?filename=" + fileName;
        modelMap.put("chartURLLine", chartURL);
        return new ModelAndView("index", modelMap);
    }
    
    
    
    
    
    // 获取柱状图数据集
    private CategoryDataset getDataSet(List<City> cityList) {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        if (cityList != null && cityList.size() > 0) {
            for (City city : cityList) {
                dataset.addValue(city.getCount(), city.getCityname(), city.getFruitname());
            }
        }
        return dataset;
    }

    // 获取饼状图数据集
    private DefaultPieDataset getDataSetpie(List<City> cityList) {
        DefaultPieDataset dataset = new DefaultPieDataset();
        // if (cityList != null && cityList.size() > 0) {
        // for (City city : cityList) {
        // dataset.addValue(city.getCount(), city.getCityname(),
        // city.getFruitname());
        // }
        // }

        dataset.setValue("北京", 13);
        dataset.setValue("深圳", 6);
        dataset.setValue("上海", 2);
        return dataset;
    }

    // 获取折线图数据集
    private DefaultCategoryDataset getDataSetLine(List<City> cityList) {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        // if (cityList != null && cityList.size() > 0) {
        // for (City city : cityList) {
        // dataset.addValue(city.getCount(), city.getCityname(),
        // city.getFruitname());
        // }
        // }
        
        dataset.addValue(13, "所属单位", "北京");
        dataset.addValue(6, "所属单位", "深圳");
        dataset.addValue(2, "所属单位", "上海");
        dataset.addValue(24, "水果", "香蕉");
        dataset.addValue(15, "水果", "梨子");
        dataset.addValue(27, "水果", "苹果");
        return dataset;
    }
}
public class JfreeUtil {

    // 柱状图
    public static void setJfreeChart(JFreeChart chart) {
        // 处理图形上的乱码
                // 处理主标题的乱码
                chart.getTitle().setFont(new Font("宋体", Font.BOLD, 18));
                // 处理子标题乱码
                chart.getLegend().setItemFont(new Font("宋体", Font.BOLD, 15));
                // 获取图表区域对象
                CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
                // 获取X轴的对象
                CategoryAxis3D categoryAxis3D = (CategoryAxis3D) categoryPlot.getDomainAxis();
                // 获取Y轴的对象
                NumberAxis3D numberAxis3D = (NumberAxis3D) categoryPlot.getRangeAxis();
                // 处理X轴上的乱码
                categoryAxis3D.setTickLabelFont(new Font("宋体", Font.BOLD, 15));
                // 处理X轴外的乱码
                categoryAxis3D.setLabelFont(new Font("宋体", Font.BOLD, 15));
                // 处理Y轴上的乱码
                numberAxis3D.setTickLabelFont(new Font("宋体", Font.BOLD, 15));
                // 处理Y轴外的乱码
                numberAxis3D.setLabelFont(new Font("宋体", Font.BOLD, 15));
                // 处理Y轴上显示的刻度,以1作为1格
                numberAxis3D.setAutoTickUnitSelection(false);
                NumberTickUnit unit = new NumberTickUnit(1);
                numberAxis3D.setTickUnit(unit);
                // 获取绘图区域对象
                BarRenderer3D barRenderer3D = (BarRenderer3D) categoryPlot.getRenderer();
                // 设置柱形图的宽度
                barRenderer3D.setMaximumBarWidth(0.07);
                // 在图形上显示数字
                barRenderer3D.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
                barRenderer3D.setBaseItemLabelsVisible(true);
                barRenderer3D.setBaseItemLabelFont(new Font("宋体", Font.BOLD, 15));
    }
    
    // 饼状图
    public static void setJfreePie(JFreeChart chart) {

        // 处理图形上的乱码
        // 处理主标题的乱码
        chart.getTitle().setFont(new Font("宋体", Font.BOLD, 18));
        // 处理子标题乱码
        chart.getLegend().setItemFont(new Font("宋体", Font.BOLD, 15));
        // 获取图表区域对象
        PiePlot3D categoryPlot = (PiePlot3D) chart.getPlot();
        // 处理图像上的乱码
        categoryPlot.setLabelFont(new Font("宋体", Font.BOLD, 15));
        // 设置图形的生成格式为(上海 2 (10%))
        String format = "{0} {1} ({2})";
        categoryPlot.setLabelGenerator(new StandardPieSectionLabelGenerator(format));
        // 使用ChartFrame对象显示图像
    }
    
    // 折线图
    public static void setJfreeLine(JFreeChart chart) {
        // 处理图形上的乱码
                // 处理主标题的乱码
                chart.getTitle().setFont(new Font("宋体", Font.BOLD, 18));
                // 处理子标题乱码
                chart.getLegend().setItemFont(new Font("宋体", Font.BOLD, 15));
                // 获取图表区域对象
                CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
                // 获取X轴的对象
                CategoryAxis categoryAxis = (CategoryAxis) categoryPlot.getDomainAxis();
                // 获取Y轴的对象
                NumberAxis numberAxis = (NumberAxis) categoryPlot.getRangeAxis();
                // 处理X轴上的乱码
                categoryAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 15));
                // 处理X轴外的乱码
                categoryAxis.setLabelFont(new Font("宋体", Font.BOLD, 15));
                // 处理Y轴上的乱码
                numberAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 15));
                // 处理Y轴外的乱码
                numberAxis.setLabelFont(new Font("宋体", Font.BOLD, 15));
                // 处理Y轴上显示的刻度,以1作为1格
                numberAxis.setAutoTickUnitSelection(false);
                NumberTickUnit unit = new NumberTickUnit(1);
                numberAxis.setTickUnit(unit);
                // 获取绘图区域对象
                LineAndShapeRenderer lineAndShapeRenderer = (LineAndShapeRenderer) categoryPlot.getRenderer();
                // 在图形上显示数字
                lineAndShapeRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
                lineAndShapeRenderer.setBaseItemLabelsVisible(true);
                lineAndShapeRenderer.setBaseItemLabelFont(new Font("宋体", Font.BOLD, 15));
                // 在图形上添加转折点(使用小矩形显示)
                Rectangle shape = new Rectangle(10, 10);
                lineAndShapeRenderer.setSeriesShape(0, shape);
                lineAndShapeRenderer.setSeriesShapesVisible(0, true);
    }
}

jsp页面

<div style="text-align: center">
        jfreechart _3D柱状图 <br>
        <br> 点击显示柱状图<a href="getColumnChart.action">getMajorChart</a> <br>
        <br> 
        <c:if test="${not empty chartURLBar}">  
        <img src="${chartURLBar}" width=600 height=400 border=0
            color=gray>
        </c:if>  
    </div>

    <div style="text-align: center">
        jfreechart _3D饼状图 <br>
        <br> 点击显示饼状图<a href="getColumnpie.action">getMajorChart</a> <br>
        <br> 
        <c:if test="${not empty chartURLPie}">  
        <img src="${chartURLPie}" width=600 height=400 border=0
            color=gray>
        </c:if>  
    </div>

    <div style="text-align: center">
        jfreechart _3D折线状图 <br>
        <br> 点击显示折线图<a href="getColumnLine.action">getMajorChart</a> <br>
        <br> 
        <c:if test="${not empty chartURLLine}">  
        <img src="${chartURLLine}" width=600 height=400 border=0
            color=gray>
        </c:if>  
    </div>

web.xml

//插入下面部分
    <servlet>
        <servlet-name>DisplayChart</servlet-name>
        <servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>DisplayChart</servlet-name>
        <url-pattern>/chart</url-pattern>
    </servlet-mapping>

</web-app>

jar包jfreechart1.0.13