利用jFreeChart插件生产各种图形的报表

利用jFreeChart插件生产各种图形的报表

1.添加基于maven的依赖包

<!-- JfreeChart报表依赖 -->    
        <dependency>
            <groupId>jfree</groupId>  
            <artifactId>jfreechart</artifactId>  
            <version>1.0.13</version>
        </dependency>     

2.修改web.xml添加JfreeChart报表设置

<!-- JfreeChart报表设置 --> 
   <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>/DisplayChart</url-pattern>
    </servlet-mapping>

3.Controller

//获得单一柱状图形报表
    @RequestMapping(value = "/ticket/getBarChart",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView getBarChart(HttpServletRequest request,
            HttpServletResponse response
             )throws Exception{
        JSONArray jsonArray = new JSONArray();//用于存放数据集
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("化学", 40);
        map.put("生物学", 50);
        map.put("物理学", 30);
        map.put("计算机", 70);
        map.put("毛中概论", 60);
        String title = "课堂人数报表";
        String DomainAxisLabelText = "课程";
        String RangeAxisLabelText = "人数";
       String chartURL = jfreeChartUtil.getSigleChart(request, title, DomainAxisLabelText, RangeAxisLabelText, map); 
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("chartURL", chartURL);
        modelAndView.setViewName("/ticket/choose/barChart");
        return modelAndView;
    }
    //获得多维柱状图形报表
        @RequestMapping(value = "/ticket/getBarChart1",method = {RequestMethod.GET,RequestMethod.POST})
        public ModelAndView getBarChart1(HttpServletRequest request,
                HttpServletResponse response
                 )throws Exception{
            double [][]data=new double[][]{{1320,1110,1123,321},{720,210,1423,1321},{830,1310,123,521},{400,1110,623,321}};
            String []rowKeys={"苹果","香蕉","橘子","梨子"};
            String []columnKeys={"深圳","北京","上海","南京"};
            String title = "水果销量报表";
            String DomainAxisLabelText = "水果";
            String RangeAxisLabelText = "销量";
            String chartURL = jfreeChartUtil.getManyChart(request, rowKeys, columnKeys, data, title, DomainAxisLabelText, RangeAxisLabelText);
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("chartURL", chartURL);
            modelAndView.setViewName("/ticket/choose/barChart");
            return modelAndView;
        }
        
    //获得饼状图形报表
                @RequestMapping(value = "/ticket/getPieChart",method = {RequestMethod.GET,RequestMethod.POST})
                public ModelAndView getPieChart(HttpServletRequest request,
                        HttpServletResponse response
                         )throws Exception{
                    String title = "万达乐园系统收入分布表";
                    String subTitle = "2017年度";
                    Map<String, Integer> dataset = new HashMap<String, Integer>();
                    dataset.put("西双版纳", 1200);
                    dataset.put("南昌", 960);
                    dataset.put("合肥", 2600);
                    dataset.put("武汉", 3000);
                    dataset.put("哈尔滨", 1300);
                    dataset.put("长白山", 1700);
                    String chartURL = jfreeChartUtil.getPieChart(request, dataset, title, subTitle);
                    ModelAndView modelAndView = new ModelAndView();
                    modelAndView.addObject("chartURL", chartURL);
                    modelAndView.setViewName("/ticket/choose/barChart");
                    return modelAndView;
                }
                
    //获得时序折线图形报表
                @RequestMapping(value = "/ticket/getTimeLineChart",method = {RequestMethod.GET,RequestMethod.POST})
                public ModelAndView getTimeLineChart(HttpServletRequest request,
                        HttpServletResponse response
                         )throws Exception{
                    List<Map<Integer, Integer>> listData = new ArrayList<Map<Integer,Integer>>();
                    Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();
                    Map<Integer, Integer> map2 = new HashMap<Integer, Integer>();
                    for(int i=1;i<13;i++){
                        map1.put(i, 300*i%1000);
                        map2.put(i, 250*i%1000);
                    }
                    listData.add(map1);
                    listData.add(map2);
                    String [] subTiles = {"A网站访问量统计","B网站访问量统计"};
                    String Tile= "网站交互量统计时间折线图";
                    String DomainAxisLabelText = "月份";
                    String RangeAxisLabelText="访问量";
                    String subTile = "2016年度";
                    String chartURL = jfreeChartUtil.genTimeLineChart1(request, listData, subTile,subTiles, Tile, DomainAxisLabelText, RangeAxisLabelText);
                    ModelAndView modelAndView = new ModelAndView();
                    modelAndView.addObject("chartURL", chartURL);
                    modelAndView.setViewName("/ticket/choose/barChart");
                    return modelAndView;
                }
    //获得折线图报表            
                @RequestMapping(value = "/ticket/getLineChart",method = {RequestMethod.GET,RequestMethod.POST})
                public ModelAndView getLineChart(HttpServletRequest request,
                        HttpServletResponse response
                         )throws Exception{
                    String chartURL = jfreeChartUtil.getLineChart(request);
                    ModelAndView modelAndView = new ModelAndView();
                    modelAndView.addObject("chartURL", chartURL);
                    modelAndView.setViewName("/ticket/choose/barChart");
                    return modelAndView;
                }
//获得全部            
                @RequestMapping(value = "/ticket/getAllChart",method = {RequestMethod.GET,RequestMethod.POST})
                public ModelAndView getAllChart(HttpServletRequest request,
                        HttpServletResponse response
                         )throws Exception{
            //折线图
                    String chartURL = jfreeChartUtil.getLineChart(request);
            //时序图        
                    List<Map<Integer, Integer>> listData = new ArrayList<Map<Integer,Integer>>();
                    Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();
                    Map<Integer, Integer> map2 = new HashMap<Integer, Integer>();
                    for(int i=1;i<13;i++){
                        map1.put(i, 300*i%1000);
                        map2.put(i, 250*i%1000);
                    }
                    listData.add(map1);
                    listData.add(map2);
                    String [] subTiles = {"A网站访问量统计","B网站访问量统计"};
                    String Tile= "网站交互量统计时间折线图";
                    String DomainAxisLabelText = "月份";
                    String RangeAxisLabelText="访问量";
                    String subTile = "2016年度";
                    String chartURL1 = jfreeChartUtil.genTimeLineChart1(request, listData, subTile,subTiles, Tile, DomainAxisLabelText, RangeAxisLabelText);
                    //饼状图
                    String title = "万达乐园系统收入分布表";
                    String subTitle = "2017年度";
                    Map<String, Integer> dataset = new HashMap<String, Integer>();
                    dataset.put("西双版纳", 1200);
                    dataset.put("南昌", 960);
                    dataset.put("合肥", 2600);
                    dataset.put("武汉", 3000);
                    dataset.put("哈尔滨", 1300);
                    dataset.put("长白山", 1700);
                    String chartURL2 = jfreeChartUtil.getPieChart(request, dataset, title, subTitle);
                    //多维柱状图
                    double [][]data=new double[][]{{1320,1110,1123,321},{720,210,1423,1321},{830,1310,123,521},{400,1110,623,321}};
                    String []rowKeys={"乐园","冰雪","秀","茂"};
                    String []columnKeys={"深圳","北京","上海","南京"};
                    String title1 = "产品销量报表";
                    String DomainAxisLabelText1 = "产品";
                    String RangeAxisLabelText1 = "销量";
                    String chartURL3 = jfreeChartUtil.getManyChart(request, rowKeys, columnKeys, data, title1, DomainAxisLabelText1, RangeAxisLabelText1);
                    ModelAndView modelAndView = new ModelAndView();
                    modelAndView.addObject("chartURL", chartURL);
                    modelAndView.addObject("chartURL1", chartURL1);
                    modelAndView.addObject("chartURL2", chartURL2);
                    modelAndView.addObject("chartURL3", chartURL3);
                    modelAndView.setViewName("/ticket/choose/barChart");
                    return modelAndView;
                }

4.jFreeChartUtil

package com.crs.ticket.wanda.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.jfree.chart.ChartColor;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryAxis3D;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberAxis3D;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.TextAnchor;

public class jfreeChartUtil {
    
//解决jfreeChart1.0.13中文乱码问题
     public static void configFont(JFreeChart chart) {
            // 配置字体
            Font font = new Font("宋体", Font.BOLD, 20);
            Font font1 = new Font("宋体", Font.BOLD, 15);

            chart.getTitle().setFont(font);//大标题
            if (chart.getLegend() != null) {
                chart.getLegend().setItemFont(font);
            }
            if (chart.getPlot() instanceof CategoryPlot && ((CategoryPlot) chart.getPlot()).getRenderer() instanceof BarRenderer3D) {//柱状图
//                chart.getCategoryPlot().getDomainAxis().setLabelFont(font);//水平底部列表
//                chart.getCategoryPlot().getDomainAxis().setTickLabelFont(font);//水平底部标题
//                chart.getCategoryPlot().getRangeAxis().setLabelFont(font);//垂直列表
//                chart.getCategoryPlot().getRangeAxis().setTickLabelFont(font);//垂直标题

                // 处理图形上的乱码
                // 处理主标题的乱码
                chart.getTitle().setFont(new Font("宋体", Font.BOLD, 18));
                // 处理子标题乱码
                if(chart.getLegend()!=null){
                    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 renderer=new BarRenderer3D();
                renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
                renderer.setBaseItemLabelsVisible(true);                
                renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
                renderer.setItemLabelAnchorOffset(10D); 
                CategoryPlot plot=chart.getCategoryPlot();
                plot.setRenderer(renderer);
            } else if (chart.getPlot() instanceof XYPlot) {//时序图
                
                //下标小图
                chart.getLegend().setItemFont(new java.awt.Font("宋体", Font.BOLD, 15));
                
                //设置时间轴的范围。
                XYPlot plot = (XYPlot) chart.getPlot();             
                DateAxis dateaxis = (DateAxis)plot.getDomainAxis();
                dateaxis.setDateFormatOverride(new java.text.SimpleDateFormat("M月"));
                dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH,1)); 
               //字体乱码处理
                plot.getDomainAxis().setLabelFont(font1);//横轴小标题字体
                plot.getDomainAxis().setTickLabelFont(font1);//横轴列表字体      
                plot.getRangeAxis().setLabelFont(font1);//竖轴小标题字体
                plot.getRangeAxis().setTickLabelFont(font1);//竖轴列表字体                
                
            //设置曲线是否显示数据点
            XYLineAndShapeRenderer xylinerenderer = (XYLineAndShapeRenderer)plot.getRenderer();
            xylinerenderer.setBaseShapesVisible(true);
            //设置曲线显示各数据点的值
            XYItemRenderer xyitem = plot.getRenderer(); 
            xyitem.setBaseItemLabelsVisible(true);
            xyitem.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER)); 
            xyitem.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
            xyitem.setBaseItemLabelFont(new Font("Dialog", 1, 12)); 
            plot.setRenderer(xyitem);
                
            } else if (chart.getPlot() instanceof PiePlot) {//饼状图
//                chart.getTitle().setFont(new Font("黑体",Font.BOLD,20));//设置饼状标题字体
//                chart.get
//                PiePlot piePlot= (PiePlot) chart.getPlot();//获取图表区域对象
//                piePlot.setLabelFont(new Font("黑体",Font.BOLD,15));
//                chart.getLegend().setItemFont(new Font("黑体",Font.BOLD,15));
                
                // 处理图形上的乱码
                // 处理主标题的乱码
                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对象显示图像
            }else{//折线图
                  // 处理图形上的乱码
                // 处理主标题的乱码
                chart.getTitle().setFont(new Font("宋体", Font.BOLD, 18));
                // 处理子标题乱码
                chart.getLegend().setItemFont(new Font("宋体", Font.BOLD, 15));
                
                // 获取图表区域对象
                CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
                
                // 设置网格竖线颜色
                categoryPlot.setDomainGridlinePaint(Color.white);
                // 设置网格横线颜色
                categoryPlot.setRangeGridlinePaint(Color.white);
                // 获取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.setBaseShapesVisible(true);
                //设置曲线显示各数据点的值
                lineAndShapeRenderer.setBaseItemLabelsVisible(true);
                lineAndShapeRenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
                lineAndShapeRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
                lineAndShapeRenderer.setBaseItemLabelFont(new Font("Dialog", 1, 12));
                categoryPlot.setRenderer(lineAndShapeRenderer);
               
                
            }
            
        }
    /**
     * 生成单一柱状图
     * @param request
     * @param title 大标题
     * @param DomainAxisLabelText 水平下标题
     * @param RangeAxisLabelText 垂直标题
     * @param jsonArray 数据集
     * @return
     * @throws IOException 
     */
     public static String getSigleChart(HttpServletRequest request,String title,String DomainAxisLabelText,String RangeAxisLabelText,Map<String, Integer> map) throws IOException{
            //1. 获得数据集合  
         DefaultCategoryDataset dataset = new DefaultCategoryDataset();
         for (Iterator<String> iterator = map.keySet().iterator();iterator.hasNext();) {
             String key = iterator.next();
            dataset.addValue(map.get(key), "",key);            
        }
        //2. 创建柱状图  
        JFreeChart chart = ChartFactory.createBarChart3D(title, // 图表标题  
                DomainAxisLabelText, // 目录轴的显示标签  
                RangeAxisLabelText, // 数值轴的显示标签  
                dataset, // 数据集  
                PlotOrientation.VERTICAL, // 图表方向:垂直  
                //PlotOrientation.HORIZONTAL //水平
                false, // 是否显示图例(对于简单的柱状图必须是false)  
                false, // 是否生成工具  
                false // 是否生成URL链接  
                );  
        //3. 设置整个柱状图的颜色和文字(char对象的设置是针对整个图形的设置)  
        chart.setBackgroundPaint(ChartColor.WHITE); // 设置总的背景颜色  
          
        //4. 获得图形对象,并通过此对象对图形的颜色文字进行设置  
        CategoryPlot p = chart.getCategoryPlot();// 获得图表对象  
        p.setBackgroundPaint(ChartColor.lightGray);//图形背景颜色  
        p.setRangeGridlinePaint(ChartColor.WHITE);//图形表格颜色  
          
        //5. 设置柱子宽度  
        BarRenderer renderer = (BarRenderer)p.getRenderer();  
        renderer.setMaximumBarWidth(0.06);  
          
        //解决乱码问题  
        jfreeChartUtil.configFont(chart);
          
        //6. 将图形转换为图片,传到前台  
        String fileName = ServletUtilities.saveChartAsPNG(chart, 700, 400, null, request.getSession());  
        String chartURL=request.getContextPath() + "/DisplayChart?filename="+fileName; 
        return chartURL;
     }
     /**
      * 生成多维柱状图
      * @param request
      * @param rowKeys 二维行数组
      * @param columnKeys 一维行数组
      * @param data 数据集合多维数组
      * @param title 大标题
      * @param DomainAxisLabelText 小横标题
      * @param RangeAxisLabelText  小竖标题
      * @return
      * @throws Exception
      */
     public static String getManyChart(HttpServletRequest request,String []rowKeys,String []columnKeys,double[][] data,String title,String DomainAxisLabelText,String RangeAxisLabelText) throws Exception {
            CategoryDataset dataset=DatasetUtilities.createCategoryDataset(rowKeys,columnKeys ,data);
            JFreeChart chart=ChartFactory.createBarChart3D(title, DomainAxisLabelText, RangeAxisLabelText, dataset,
                    PlotOrientation.VERTICAL, true, true, true);
            jfreeChartUtil.configFont(chart);
            String fileName=ServletUtilities.saveChartAsPNG(chart, 700, 500, null,request.getSession());
            String chartURL=request.getContextPath() + "/DisplayChart?filename="+fileName; 
            return chartURL;
        } 
     /**
      * 生成饼状图报表
      * @param request
      * @param dataset 数据集
      * @param title 大标题
      * @param subTitle 小标题
      * @return
      * @throws Exception
      */
     public static String getPieChart(HttpServletRequest request,Map<String, Integer>map,String title,String subTitle) throws Exception {
            DefaultPieDataset dataset = new DefaultPieDataset();
            for(Iterator<String>iterator = map.keySet().iterator();iterator.hasNext();){
                String key = iterator.next();
                dataset.setValue(key, map.get(key));
            }

            //设置3D属性
            JFreeChart chart=ChartFactory.createPieChart3D(title, dataset, true, true, true);
//            PiePlot3D pieplot3d = (PiePlot3D) chart.getPlot();
//            //设置开始角度  
//            pieplot3d.setStartAngle(120D);  
//            //设置方向为”顺时针方向“  
//            pieplot3d.setDirection(Rotation.CLOCKWISE);  
//            //设置透明度,0.5F为半透明,1为不透明,0为全透明  
//            pieplot3d.setForegroundAlpha(0.7F); 
            
            // 副标题
            chart.addSubtitle(new TextTitle(subTitle));
            
            PiePlot pieplot=(PiePlot)chart.getPlot();
            pieplot.setLabelFont(new Font("宋体",0,11));
            // 设置饼图是圆的(true),还是椭圆的(false);默认为true  
            pieplot.setCircular(true);
            // 没有数据的时候显示的内容
            pieplot.setNoDataMessage("无数据显示");
            StandardPieSectionLabelGenerator standarPieIG = new StandardPieSectionLabelGenerator("{0}:({1}.{2})", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()); 
            //突出显示某一块
//            pieplot.setLabelGenerator(standarPieIG);  
//            pieplot.setExplodePercent("城管强拆",0.23); 
//            pieplot.setLabelGenerator(standarPieIG);  
            jfreeChartUtil.configFont(chart);
            String fileName=ServletUtilities.saveChartAsPNG(chart, 700, 500, null, request.getSession());
            String chartURL=request.getContextPath() + "/DisplayChart?filename="+fileName; 
            return chartURL;
        }
/**
 * 单曲线时序图
 * @param request
 * @return
 * @throws Exception
 */
        public static String genTimeLineChart(HttpServletRequest request)throws Exception{
            
            // 访问量统计
            TimeSeries timeSeries=new TimeSeries("某网站访问量统计", Month.class);
            // 添加数据
            timeSeries.add(new Month(1,2013), 100);
            timeSeries.add(new Month(2,2013), 200);
            timeSeries.add(new Month(3,2013), 300);
            timeSeries.add(new Month(4,2013), 400);
            timeSeries.add(new Month(5,2013), 560);
            timeSeries.add(new Month(6,2013), 600);
            timeSeries.add(new Month(7,2013), 750);
            timeSeries.add(new Month(8,2013), 890);
            timeSeries.add(new Month(9,2013), 120);
            timeSeries.add(new Month(10,2013), 400);
            timeSeries.add(new Month(11,2013), 1200);
            timeSeries.add(new Month(12,2013), 1600);
            
            // 定义时间序列的集合
            TimeSeriesCollection lineDataset=new TimeSeriesCollection();
            lineDataset.addSeries(timeSeries);
            
            JFreeChart chart=ChartFactory.createTimeSeriesChart("访问量统计时间折线图", "月份", "访问量", lineDataset, true, true, true);
            
            //设置主标题
            chart.setTitle(new TextTitle("某网站访问量统计", new Font("隶书", Font.ITALIC, 15))); 
            //设置子标题
            TextTitle subtitle = new TextTitle("2013年度", new Font("黑体", Font.BOLD, 12));
            chart.addSubtitle(subtitle); 
            chart.setAntiAlias(true); 
            
            //设置时间轴的范围。
            XYPlot plot = (XYPlot) chart.getPlot(); 
            DateAxis dateaxis = (DateAxis)plot.getDomainAxis();
            dateaxis.setDateFormatOverride(new java.text.SimpleDateFormat("M月"));
            dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH,1)); 
            
            //设置曲线是否显示数据点
            XYLineAndShapeRenderer xylinerenderer = (XYLineAndShapeRenderer)plot.getRenderer();
            xylinerenderer.setBaseShapesVisible(true); 
            
            //设置曲线显示各数据点的值
            XYItemRenderer xyitem = plot.getRenderer(); 
            xyitem.setBaseItemLabelsVisible(true);
            xyitem.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER)); 
            xyitem.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
            xyitem.setBaseItemLabelFont(new Font("Dialog", 1, 12)); 
            plot.setRenderer(xyitem);
            jfreeChartUtil.configFont(chart);
            String fileName=ServletUtilities.saveChartAsPNG(chart, 700, 500, request.getSession());
            String chartURL=request.getContextPath() + "/DisplayChart?filename="+fileName; 
            return chartURL;
        }
/**
 * 多曲线时序图
 * @param request
 * @param listData 数据集
 * @param subTitle 曲线小标题
 * @param title 大标题
 * @param DomainAxisLabelText 横向小标题
 * @param RangeAxisLabelText 纵向小标题
 * @return
 * @throws Exception
 */
        public static String genTimeLineChart1(HttpServletRequest request,List<Map<Integer, Integer>> listData,String subTile,String[]subTitles,String title,String DomainAxisLabelText,String RangeAxisLabelText)throws Exception{
            // 定义时间序列的集合
            TimeSeriesCollection lineDataset=new TimeSeriesCollection();
            for(int i=0;i<subTitles.length;i++){
                // 访问量统计
                TimeSeries timeSeries =new TimeSeries(subTitles[i], Month.class);
                Map<Integer, Integer> map = listData.get(i);
                // 添加数据
                for(Iterator<Integer> iterator = map.keySet().iterator();iterator.hasNext();){
                    Integer key = iterator.next();
                    timeSeries.add(new Month(key,2013), map.get(key));
                }
                lineDataset.addSeries(timeSeries);
            }

            
            JFreeChart chart=ChartFactory.createTimeSeriesChart(title, DomainAxisLabelText, RangeAxisLabelText, lineDataset, true, true, true);
            //设置子标题
            TextTitle subtitle = new TextTitle(subTile, new Font("黑体", Font.BOLD, 12));
            chart.addSubtitle(subtitle); 
            chart.setAntiAlias(true); 
            
            jfreeChartUtil.configFont(chart);            
            String fileName=ServletUtilities.saveChartAsPNG(chart, 700, 500, request.getSession());
            String chartURL=request.getContextPath() + "/DisplayChart?filename="+fileName; 
            return chartURL;
        }
/**
 * 多折线图
 * @param request
 * @return
 * @throws Exception
 */
        public static  String getLineChart(HttpServletRequest request)
                throws Exception {
            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            dataset.addValue(13, "A类用户数量", "北京");
            dataset.addValue(6, "A类用户数量", "深圳");
            dataset.addValue(2, "A类用户数量", "上海");
            dataset.addValue(24, "A类用户数量", "广州");
            dataset.addValue(15, "A类用户数量", "长春");
            dataset.addValue(27, "A类用户数量", "沈阳");
            dataset.addValue(20, "B类用户数量", "北京");
            dataset.addValue(6, "B类用户数量", "深圳");
            dataset.addValue(5, "B类用户数量", "上海");
            dataset.addValue(14, "B类用户数量", "广州");
            dataset.addValue(15, "B类用户数量", "长春");
            dataset.addValue(30, "B类用户数量", "沈阳");
        
                        
            JFreeChart chart = ChartFactory.createLineChart("用户统计报表(所属单位)", // 主标题的名称
                    "所属单位名称", // X轴的标签
                    "数量", // Y轴的标签
                    dataset, // 图标显示的数据集合
                    PlotOrientation.VERTICAL, // 图像的显示形式(水平或者垂直)
                    true, // 是否显示子标题
                    true, // 是否生成提示的标签
                    true); // 是否生成URL链接
            
           jfreeChartUtil.configFont(chart);
            
            // 6. 将图形转换为图片,传到前台
            String fileName = ServletUtilities.saveChartAsJPEG(chart, 700, 400, null, request.getSession());
            String chartURL=request.getContextPath() + "/DisplayChart?filename="+fileName; 
            return chartURL;
           
        }
}

5.前端显示char.jsp

<%@page import="com.crs.ticket.wanda.utils.jfreeChartUtil"%>
<%@ 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>
<%@ include file="/view/common/resource.jsp" %>
<%@ include file="/view/common/tags.jsp" %>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<style type="text/css">
  .first{width: 400px; height: 300px; float: left}
  body{ text-align: center}
</style>
</head>
<body >

 <div >
     <img src="${chartURL}"  width=580 height=400  border=0  color=gray>
     <img src="${chartURL1}"  width=580 height=400  border=0  color=gray>    
 </div>
 
 <div>
    <img src="${chartURL2}"  width=580 height=400  border=0  color=gray>
    <img src="${chartURL3}"  width=580 height=400  border=0  color=gray>
 </div>
 
</body>
</html>

 

posted @ 2017-09-08 10:02  十月围城小童鞋  阅读(434)  评论(0编辑  收藏  举报