JFreeChart折线图,x轴为时间

Bean代码 复制代码  收藏代码
  1. package com.potevio.rnd.tobacco.mine;   
  2.   
  3. import java.util.Map;   
  4.   
  5. /**   
  6.  * @description 数据BEAN   
  7.  * @author Zhou-Jingxian   
  8.  */   
  9. public class Bean {   
  10.   
  11.     private String goods_name ;   
  12.     private Map<String,Double> priceindexMap;   
  13.        
  14.     public String getGoods_name() {   
  15.         return goods_name;   
  16.     }   
  17.     public void setGoods_name(String goods_name) {   
  18.         this.goods_name = goods_name;   
  19.     }   
  20.   
  21.     public Map<String, Double> getPriceindexMap() {   
  22.         return priceindexMap;   
  23.     }   
  24.     public void setPriceindexMap(Map<String, Double> priceindexMap) {   
  25.         this.priceindexMap = priceindexMap;   
  26.     }   
  27.        
  28.        
  29. }  
    Timeserieschartutil 代码 复制代码  收藏代码
    1. package com.potevio.rnd.tobacco.mine;   
    2.   
    3. import java.awt.Color;   
    4. import java.awt.Font;   
    5. import java.awt.GradientPaint;   
    6. import java.io.File;   
    7. import java.io.FileNotFoundException;   
    8. import java.io.FileOutputStream;   
    9. import java.io.IOException;   
    10. import java.util.Iterator;   
    11. import java.util.List;   
    12. import java.util.Map;   
    13. import java.util.Set;   
    14.   
    15. import org.jfree.chart.ChartFactory;   
    16. import org.jfree.chart.ChartUtilities;   
    17. import org.jfree.chart.JFreeChart;   
    18. import org.jfree.chart.labels.ItemLabelAnchor;   
    19. import org.jfree.chart.labels.ItemLabelPosition;   
    20. import org.jfree.chart.labels.StandardXYItemLabelGenerator;   
    21. import org.jfree.chart.plot.XYPlot;   
    22. import org.jfree.chart.renderer.xy.XYItemRenderer;   
    23. import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;   
    24. import org.jfree.chart.title.TextTitle;   
    25. import org.jfree.data.time.Month;   
    26. import org.jfree.data.time.TimeSeries;   
    27. import org.jfree.data.time.TimeSeriesCollection;   
    28. import org.jfree.ui.RectangleInsets;   
    29. import org.jfree.ui.TextAnchor;   
    30.   
    31. /**   
    32.  * @description 使用JFreeChart组建,生成一个价格随日期的走势图表   
    33.  * @author Zhou-Jingxian   
    34.  */   
    35. public class TimeSeriesChartUtil {    
    36.        
    37.     private String type;//month,year   
    38.     private int width ;//后台计算   
    39.     private int height;//后台计算   
    40.     private String title;//图表的主标题   
    41.     private String subTitle;//图表的子标题   
    42.     private String xName;//可默认值:月份   
    43.     private String yName;//可默认值:价格指数   
    44.        
    45.     /***   
    46.      * constructor function   
    47.      * @param type   
    48.      * @param title   
    49.      * @param subTitle   
    50.      * @param xName   
    51.      * @param yName   
    52.      */   
    53.     public TimeSeriesChartUtil(String type,String title,String subTitle,String xName,String yName){   
    54.         this.type = type;   
    55.         this.title = title;   
    56.         this.subTitle = subTitle;   
    57.         this.xName = xName;   
    58.         this.yName = yName;   
    59.         if("month".equals(type)){   
    60.             this.width = 800;   
    61.             this.height = 600;   
    62.         }else if("year".equals(type)){   
    63.             this.width = 600;   
    64.             this.height = 400;   
    65.         }   
    66.     }   
    67.        
    68.     /** 根据TimeSeriesCollection创建JFreeChart对象*/      
    69.     public JFreeChart createChart(TimeSeriesCollection dataset) {      
    70.            
    71.         JFreeChart chart = ChartFactory.createTimeSeriesChart(this.title, this.xName,this.yName, dataset, true, true, true);   
    72.            
    73.         XYPlot plot = (XYPlot) chart.getPlot();   
    74.         XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer)plot.getRenderer();   
    75.         //设置网格背景颜色   
    76.         plot.setBackgroundPaint(Color.white);   
    77.         //设置网格竖线颜色   
    78.         plot.setDomainGridlinePaint(Color.pink);   
    79.         //设置网格横线颜色   
    80.         plot.setRangeGridlinePaint(Color.pink);   
    81.         //设置曲线图与xy轴的距离   
    82.         plot.setAxisOffset(new RectangleInsets(0D, 0D, 0D, 10D));   
    83.         //设置曲线是否显示数据点   
    84.         xylineandshaperenderer.setBaseShapesVisible(true);   
    85.         //设置曲线显示各数据点的值   
    86.         XYItemRenderer xyitem = plot.getRenderer();      
    87.         xyitem.setBaseItemLabelsVisible(true);      
    88.         xyitem.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));   
    89.         xyitem.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());   
    90.         xyitem.setBaseItemLabelFont(new Font("Dialog"114));   
    91.         plot.setRenderer(xyitem);   
    92.            
    93.         //设置子标题   
    94.         TextTitle subtitle = new TextTitle(this.subTitle, new Font("黑体", Font.BOLD, 12));   
    95.         chart.addSubtitle(subtitle);   
    96.         //设置主标题   
    97.         chart.setTitle(new TextTitle(this.title, new Font("隶书", Font.ITALIC, 15)));   
    98.         //设置背景颜色   
    99.         chart.setBackgroundPaint(new GradientPaint(00, Color.white, 01000,Color.blue));   
    100.         chart.setAntiAlias(true);   
    101.      
    102.         return chart;      
    103.     }      
    104.      
    105.     /**创建TimeSeriesCollection对象  */   
    106.     public TimeSeriesCollection createDataset(List<Bean> datalist){   
    107.            
    108.         //时间曲线数据集合   
    109.         TimeSeriesCollection lineDataset = new TimeSeriesCollection();   
    110.         for(int i=0;i<datalist.size();i++){   
    111.             Bean bean = datalist.get(i);   
    112.             TimeSeries series = new TimeSeries(bean.getGoods_name(),Month.class);   
    113.             Map<String,Double> pimap = bean.getPriceindexMap();    
    114.             Set piset = pimap.entrySet();      
    115.             Iterator piIterator = piset.iterator();      
    116.             while(piIterator.hasNext()){      
    117.                 Map.Entry<String,Double> hiddenMapEntry = (Map.Entry<String,Double>)piIterator.next();     
    118.                 String key = hiddenMapEntry.getKey();      
    119.                 int year = Integer.parseInt(key.substring(0,4));   
    120.                 int month = Integer.parseInt(key.substring(46));   
    121.                 series.add(new Month(month,year),hiddenMapEntry.getValue());   
    122.             }     
    123.             lineDataset.addSeries(series);   
    124.         }   
    125.         return lineDataset;   
    126.     }   
    127.        
    128.     /**保存为文件*/      
    129.     public void saveAsFile(JFreeChart chart, String outputPath) {      
    130.         FileOutputStream out = null;      
    131.         try {      
    132.             File outFile = new File(outputPath);      
    133.             if (!outFile.getParentFile().exists()) {      
    134.                 outFile.getParentFile().mkdirs();      
    135.             }      
    136.             out = new FileOutputStream(outputPath);      
    137.             // 保存为PNG      
    138.             ChartUtilities.writeChartAsPNG(out, chart, width, height);      
    139.             // 保存为JPEG      
    140.             // ChartUtilities.writeChartAsJPEG(out, chart, width, height);      
    141.             out.flush();      
    142.         } catch (FileNotFoundException e) {      
    143.             e.printStackTrace();      
    144.         } catch (IOException e) {      
    145.             e.printStackTrace();      
    146.         } finally {      
    147.             if (out != null) {      
    148.                 try {      
    149.                     out.close();      
    150.                 } catch (IOException e) {      
    151.                     // do nothing      
    152.                 }      
    153.             }      
    154.         }      
    155.     }      
    156.      
    157.     public int getWidth() {   
    158.         return width;   
    159.     }   
    160.   
    161.     public void setWidth(int width) {   
    162.         this.width = width;   
    163.     }   
    164.   
    165.     public int getHeight() {   
    166.         return height;   
    167.     }   
    168.   
    169.     public void setHeight(int height) {   
    170.         this.height = height;   
    171.     }      
    172.        
    173.     public String getXName() {   
    174.         return xName;   
    175.     }   
    176.   
    177.     public void setXName(String name) {   
    178.         xName = name;   
    179.     }   
    180.   
    181.     public String getYName() {   
    182.         return yName;   
    183.     }   
    184.   
    185.     public void setYName(String name) {   
    186.         yName = name;   
    187.     }   
    188.   
    189.     public String getType() {   
    190.         return type;   
    191.     }   
    192.   
    193.     public void setType(String type) {   
    194.         this.type = type;   
    195.     }   
    196.   
    197.   
    198.     public String getTitle() {   
    199.         return title;   
    200.     }   
    201.   
    202.     public void setTitle(String title) {   
    203.         this.title = title;   
    204.     }   
    205.   
    206.     public String getSubTitle() {   
    207.         return subTitle;   
    208.     }   
    209.   
    210.     public void setSubTitle(String subTitle) {   
    211.         this.subTitle = subTitle;   
    212.     }   
    213.   
    214. }  
    1. package com.potevio.rnd.tobacco.mine;   
    2.   
    3. import java.util.ArrayList;   
    4. import java.util.HashMap;   
    5. import java.util.List;   
    6. import java.util.Map;   
    7.   
    8. import org.jfree.chart.JFreeChart;   
    9. import org.jfree.data.time.TimeSeriesCollection;   
    10.   
    11.   
    12. /**   
    13.  * @description 构造数据,测试图片生成   
    14.  * @author Zhou-Jingxian   
    15.  */   
    16. public class Main {   
    17.          
    18.     public static void main(String[] args) {   
    19.            
    20.         TimeSeriesChartUtil util = new TimeSeriesChartUtil("year""重点品牌价格走势图""2009年8-10月走势图""时间""价格指数");   
    21.         List<Bean> datalist = new ArrayList<Bean>();   
    22.            
    23.         Bean bean1 = new Bean();   
    24.         bean1.setGoods_name("中华");   
    25.         Map<String,Double> priceindexMap1 = new HashMap<String,Double>();   
    26.         priceindexMap1.put("200903"99.86);   
    27.         priceindexMap1.put("200904"99.8);   
    28.         priceindexMap1.put("200905"99.97);   
    29.         priceindexMap1.put("200906"99.96);   
    30.         priceindexMap1.put("200907"99.86);   
    31.         priceindexMap1.put("200908"99.8);   
    32.         priceindexMap1.put("200909"99.97);   
    33.         priceindexMap1.put("200910"99.96);   
    34.         bean1.setPriceindexMap(priceindexMap1);   
    35.         datalist.add(bean1);   
    36.            
    37.         Bean bean2 = new Bean();   
    38.         bean2.setGoods_name("芙蓉王");   
    39.         Map<String,Double> priceindexMap2 = new HashMap<String,Double>();   
    40.         priceindexMap2.put("200903"100.12);   
    41.         priceindexMap2.put("200904"100.2);   
    42.         priceindexMap2.put("200905"100.0);   
    43.         priceindexMap2.put("200906"100.08);   
    44.         priceindexMap2.put("200907"100.12);   
    45.         priceindexMap2.put("200908"100.2);   
    46.         priceindexMap2.put("200909"100.0);   
    47.         priceindexMap2.put("200910"100.08);   
    48.         bean2.setPriceindexMap(priceindexMap2);   
    49.         datalist.add(bean2);   
    50.            
    51.         Bean bean3 = new Bean();   
    52.         bean3.setGoods_name("云烟");   
    53.         Map<String,Double> priceindexMap3 = new HashMap<String,Double>();   
    54.         priceindexMap3.put("200903"99.77);   
    55.         priceindexMap3.put("200904"99.7);   
    56.         priceindexMap3.put("200905"99.83);   
    57.         priceindexMap3.put("200906"99.93);   
    58.         priceindexMap3.put("200907"99.77);   
    59.         priceindexMap3.put("200908"99.7);   
    60.         priceindexMap3.put("200909"99.83);   
    61.         priceindexMap3.put("200910"99.93);   
    62.         bean3.setPriceindexMap(priceindexMap3);   
    63.         datalist.add(bean3);   
    64.            
    65.         //步骤1:创建XYDataset对象(准备数据)    
    66.         TimeSeriesCollection dataset = util.createDataset(datalist);   
    67.         //步骤2:根据Dataset 生成JFreeChart对象,以及做相应的设置    
    68.         JFreeChart freeChart = util.createChart(dataset);   
    69.            
    70.         //步骤3:将JFreeChart对象输出到文件,Servlet输出流等      
    71.         util.saveAsFile(freeChart, "F:\\jfreechart\\lineXY_"+Math.random()*20+".png");      
    72.     }      
    73.      



--------------------------------------------------以上转载http://zhoujingxian.iteye.com/blog/563309------------------------------------------------

package servlet;






import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockContainer;
import org.jfree.chart.block.BorderArrangement;
import org.jfree.chart.block.EmptyBlock;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.CompositeTitle;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.RectangleEdge;


import pojo.MyChart;


public class CImageServlet extends HttpServlet {


/**

*/
private static final long serialVersionUID = 4878248359669413787L;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {   
String imageName =ServletUtilities.saveChartAsJPEG(createChart(), 500, 300, request.getSession());
String imageURL = request.getContextPath() + "/servlet/DisplayChart?filename=" + imageName;  
    request.setAttribute("imageURL", imageURL);  
    request.getRequestDispatcher("/result.jsp").forward(request, response);


    }  
      
   // 保存为文件  
   public static void saveAsFile(JFreeChart chart, String outputPath,  
           int weight, int height) {  
       FileOutputStream out = null;  
       try {  
           File outFile = new File(outputPath);  
           if (!outFile.getParentFile().exists()) {  
               outFile.getParentFile().mkdirs();  
           }  
           out = new FileOutputStream(outputPath);  
 
           // 保存为PNG  
           ChartUtilities.writeChartAsPNG(out, chart,500, 400);  
           // 保存为JPEG  
           // ChartUtilities.writeChartAsJPEG(out, chart, 500, 400);  
           out.flush();  
       } catch (FileNotFoundException e) {  
           e.printStackTrace();  
       } catch (IOException e) {  
           e.printStackTrace();  
       } finally {  
           if (out != null) {  
               try {  
                   out.close();  
               } catch (IOException e) {  
                   // do nothing  
               }  
           }  
       }  
   } 
public static JFreeChart createChart() {  
       // 创建JFreeChart对象:ChartFactory.createXYLineChart  
       JFreeChart jfreechart = ChartFactory.createTimeSeriesChart("折线模型图",  
               "年份", "数量", createXYDataset() , false, true, false);  
       jfreechart.getTitle().setFont(new Font("宋体", Font.BOLD, 12));  
       // 使用CategoryPlot设置各种参数。以下设置可以省略。  
       XYPlot plot = (XYPlot) jfreechart.getPlot();  
       // 背景色 透明度  
       plot.setBackgroundAlpha(0.5f);  
       // 前景色 透明度  
       plot.setForegroundAlpha(0.5f);  
       // 其它设置可以参考XYPlot类  
       ValueAxis categoryaxis = plot.getDomainAxis(); // 横轴上的  
       categoryaxis.setPositiveArrowVisible(true);// 增加横轴的箭头  
       plot.getRangeAxis().setPositiveArrowVisible(true);// 增加纵轴的箭头  
       categoryaxis.setTickLabelFont(new Font("宋体", 10, 12));// 设定字体、类型、字号  
       DateAxis axis = (DateAxis) plot.getDomainAxis();  
       axis.setDateFormatOverride(new SimpleDateFormat("yyyy年MM月")); //x轴上面坐标为日期,显示格式为xxxx年xx月
       NumberAxis numberaxis = new NumberAxis("统计报表");//侧面显示的标题  
       numberaxis.setAutoRangeIncludesZero(false);  
       plot.setRangeAxis(1, numberaxis);  
       plot.setDataset(1, createXYDataset() );  
       plot.mapDatasetToRangeAxis(1, 1);  
       XYItemRenderer xyitemrenderer = plot.getRenderer();  
       StandardXYItemRenderer standardxyitemrenderer1 = new StandardXYItemRenderer();  
       standardxyitemrenderer1.setSeriesPaint(0, Color.black);  
       standardxyitemrenderer1.setSeriesPaint(0, Color.black);  
       standardxyitemrenderer1.setPlotLines(true);  
       LegendTitle legendtitle = new LegendTitle(xyitemrenderer);  
       LegendTitle legendtitle1 = new LegendTitle(standardxyitemrenderer1);  
       BlockContainer blockcontainer = new BlockContainer(  
               new BorderArrangement());  
       blockcontainer.add(legendtitle, RectangleEdge.LEFT);  
       blockcontainer.add(legendtitle1, RectangleEdge.RIGHT);//这两行代码可以控制位置  
       blockcontainer.add(new EmptyBlock(2000D, 0.0D));  
       CompositeTitle compositetitle = new CompositeTitle(blockcontainer);  
       compositetitle.setPosition(RectangleEdge.BOTTOM);//放置图形代表区域位置的代码  
       jfreechart.addSubtitle(compositetitle);  
       Font font2 = new Font("宋体", 10, 16); // 设定字体、类型、字号  
       plot.getDomainAxis().setLabelFont(font2);// 相当于横轴或理解为X轴  
       plot.getRangeAxis().setLabelFont(font2);// 相当于竖轴理解为Y轴  
       return jfreechart;  
   }  
/** 
    * 创建XYDataset对象 
* @throws ParseException 
    *  
    */  
   public static XYDataset createXYDataset() {  
       TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();  
       List<String> names =new ArrayList<String>();
       String rerendai="人人贷";
       String yirendai="宜人贷";
       String wenzhoudai="温州贷";
       String xiyongdai="信用贷";
       String caifudai="财富贷";
       String guojidai="国际贷";
       names.add(rerendai);
       names.add(yirendai);
       names.add(wenzhoudai);
       names.add(xiyongdai);
       names.add(caifudai);
       names.add(guojidai);
       SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
       Date date1=null;
       Date date2=null;
       Date date3=null;
       Date date4=null;
       Date date5=null;
       Date date6=null;
try {
date1 = formatDate.parse("2012-1-1");
date2  =formatDate.parse("2012-2-1");
        date3 =formatDate.parse("2012-3-1");
        date4 =formatDate.parse("2012-4-1");
        date5 =formatDate.parse("2012-5-1");
        date6 =formatDate.parse("2012-6-1");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
       
       List<MyChart> mcs = new ArrayList<MyChart>();
       MyChart myChart1=new MyChart();
       myChart1.setDate(date1);
       myChart1.setScore(12);
       MyChart myChart2=new MyChart();
       myChart2.setDate(date2);
       myChart2.setScore(8);
       MyChart myChart3=new MyChart();
       myChart3.setDate(date3);
       myChart3.setScore(10);
       MyChart myChart4=new MyChart();
       myChart4.setDate(date4);
       myChart4.setScore(20);
       MyChart myChart5=new MyChart();
       myChart5.setDate(date5);
       myChart5.setScore(22);
       MyChart myChart6=new MyChart();
       myChart6.setDate(date6);
       myChart6.setScore(2);
       mcs.add(myChart1);
       mcs.add(myChart2);
       mcs.add(myChart3);
       mcs.add(myChart4);
       mcs.add(myChart5);
       mcs.add(myChart6);
       for (String name : names) {  
           TimeSeries timeseries = new TimeSeries(name);  
           for (MyChart mc : mcs) {  
               Calendar cc = Calendar.getInstance();  
               cc.setTime(mc.getDate());  
               timeseries.add(new Month(cc.get(Calendar.MONTH)+1, cc  
                       .get(Calendar.YEAR)), mc.getScore());  
 
           }  
           timeseriescollection.addSeries(timeseries);  
 
       }  
 
       return timeseriescollection;  
   }  


}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值