jfreechart 时序图 ,生成图表

1 最终效果图

jfreechart 时序图 ,生成图表_第1张图片


2 代码

package com.cpcnet.util;

import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
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.entity.StandardEntityCollection;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.XYPlot;
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.time.Day;
import org.jfree.data.time.Minute;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.RectangleInsets;
 
/**
* @author caiwb 曲线图的绘制
*/
public class JFreeChartUtil
{
    /**
     * 返回生成图片的文件名
     * @param session
     * @param pw
     * @return 生成图片的文件名
     * @throws ParseException 
     */
    public JFreeChart getLineXYChart( XYDataset dataset,String downOrUpStream,String timeStr) throws ParseException
    {
        //初始化chart的x值
    	String xName = this.getXName(timeStr);
        String fileName = null;
        //建立JFreeChart
        JFreeChart chart = ChartFactory.createTimeSeriesChart(
        		downOrUpStream, // title
        		xName, // x-axis label
                "", // y-axis label
                dataset, // data
                true, // create legend?
                true, // generate tooltips?
                false // generate URLs?
                );
//        //设置JFreeChart的显示属性,对图形外部部分进行调整
//        chart.setBackgroundPaint(Color.gray);//设置曲线图背景色
        //设置字体大小,形状
        Font font = new Font("宋体", Font.BOLD, 16);
        TextTitle title = new TextTitle(downOrUpStream, font);
        chart.setTitle(title);
 
        XYPlot plot = (XYPlot) chart.getPlot();//获取图形的画布
        plot.setBackgroundPaint(Color.white);//设置网格背景色
        plot.setDomainGridlinePaint(Color.gray);//设置网格竖线(Domain轴)颜色
        plot.setRangeGridlinePaint(Color.gray);//设置网格横线颜色
        plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));//设置曲线图与xy轴的距离
        plot.setDomainCrosshairVisible(true);
        plot.setRangeCrosshairVisible(true);
        plot.setNoDataMessage("no data");
        XYItemRenderer r = plot.getRenderer();
       
        //设置整个chart背景颜色
        Color c = new Color(230,230,230);
        chart.setBackgroundPaint(c);
        //设置ValueAxis类
        ValueAxis valueAxis = plot.getDomainAxis();
        valueAxis.setAutoTickUnitSelection(true);
        
//      设置 x轴最大值和最小值
        this.setXValue(plot, timeStr);
//        dateAxis.setRange(this.changeStingToDate("2015-02-01 00:00:00"),this.changeStingToDate("2015-02-27 23:59:59")); //
      
         //设置Y轴
        NumberAxis numAxis = (NumberAxis) plot.getRangeAxis();
        NumberFormat numFormater = NumberFormat.getNumberInstance();
        numFormater.setMinimumFractionDigits(4);
        numAxis.setNumberFormatOverride(numFormater);
 
 
        //设置X轴(日期轴)
        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));
 
        ChartRenderingInfo info = new ChartRenderingInfo(
                new StandardEntityCollection());

        return chart;//返回生成图片的文件名
    }
    
    /*
     * 设置x轴最大值和最小值
     * */
    public void setXValue( XYPlot plot,String timeStr){
    	DateAxis dateAxis = (DateAxis)plot.getDomainAxis();
   	 	String firstDay = LastMonthUtil.getLastMonthFirstDay(timeStr);
   	 	String lastDay = LastMonthUtil.getLastMonthLastDay(timeStr);
    	try {
			dateAxis.setRange(this.changeStingToDate(firstDay),this.changeStingToDate(lastDay));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //
    	
    }
    /*
     * 设置x轴名称
     * */
    public String getXName(String timeStr ){
    	int year = Integer.parseInt(timeStr.split(" ")[0].split("-")[0]);
		int month = Integer.parseInt(timeStr.split(" ")[0].split("-")[1]);
		String monthStr;
		switch(month){
			case 1: monthStr = "Jan";break;
			case 2: monthStr = "Feb";break;
			case 3: monthStr = "Mar";break;
			case 4: monthStr = "Apr";break;
			case 5: monthStr = "May";break;
			case 6: monthStr = "Jun";break;
			case 7: monthStr = "Jul";break;
			case 8: monthStr = "Aug";break;
			case 9: monthStr = "Sep";break;
			case 10: monthStr = "Oct";break;
			case 11: monthStr = "Nov";break;
			case 12: monthStr = "Dec";break;
			default :  monthStr = "error";break;
		 }
		String name = monthStr + " " + year;
		
		return name;
		
    }
    
    /**
     * 建立生成图形所需的数据集
     * @return 返回数据集
     * @throws ParseException 
     */
    private XYDataset createDateSet() throws ParseException
    {
        TimeSeriesCollection dataset = new TimeSeriesCollection();//时间曲线数据集合
        TimeSeries s1 = new TimeSeries("quxian1", Minute.class);//创建时间数据源,每一个//TimeSeries在图上是一条曲线
        TimeSeries s2 = new TimeSeries("quxian2", Minute.class);//创建时间数据源,每一个//TimeSeries在图上是一条曲线
        //s1.add(new Day(day,month,year),value),添加数据点信息
        String time1 = "2015-02-01 00:00:00";
        String time2 = "2015-02-09 22:16:27";
        String time3 = "2015-02-09 22:21:27";
        String time4 = "2015-02-10 22:26:27";
        String time5 = "2015-02-10 22:31:27";
        String time6 = "2015-02-09 22:36:27";
        String time7 = "2015-02-10 22:41:27";
        String time8 = "2015-02-09 22:46:27";
        String time9 = "2015-02-09 22:51:27";
        String time10 = "2015-02-27 23:16:27";

        s1.add(new Minute(this.changeStingToDate(time2)),126.51);
        s1.add(new Minute(this.changeStingToDate(time3)),153.51);
        s1.add(new Minute(this.changeStingToDate(time4)),158); 
        s1.add(new Minute(this.changeStingToDate(time5)),133.51);
        s1.add(new Minute(this.changeStingToDate(time6)),123.51);
        s1.add(new Minute(this.changeStingToDate(time7)),136);
        s1.add(new Minute(this.changeStingToDate(time8)),173.51);
        s1.add(new Minute(this.changeStingToDate(time9)),193.51); 
        s1.add(new Minute(this.changeStingToDate(time10)),183.51);
        
        s2.add(new Minute(this.changeStingToDate(time2)),226.51);
        s2.add(new Minute(this.changeStingToDate(time3)),253.51);
        s2.add(new Minute(this.changeStingToDate(time4)),235); 
        s2.add(new Minute(this.changeStingToDate(time5)),233.51);
        s2.add(new Minute(this.changeStingToDate(time6)),223.51);
        s2.add(new Minute(this.changeStingToDate(time7)),256);
        s2.add(new Minute(this.changeStingToDate(time8)),273.51);
        s2.add(new Minute(this.changeStingToDate(time9)),293.51); 
        s2.add(new Minute(this.changeStingToDate(time10)),283.51);
        

        dataset.addSeries(s1);
        dataset.addSeries(s2);
        dataset.setDomainIsPointsInTime(true);
        return dataset;
    }
    
    public void saveImage(JFreeChart chart,String fileName){
    	 String imageName = "d:/chartTest/XYLineChart.png";
         try {   
             //年的用600*400;月的用800*400,用PNG生生成的图片比较清楚   
             ChartUtilities.saveChartAsPNG(new File(imageName), chart, 640, 360);   
         } catch (IOException exz) {   
             System.out.print("....Cant’t Create image File");   
         }  
    }
    
    public static void main(String args[]) throws ParseException{
    	JFreeChartUtil jFreeChartUtil = new JFreeChartUtil();
        XYDataset dataset = jFreeChartUtil.createDateSet();//建立数据集
    	JFreeChart chart = jFreeChartUtil.getLineXYChart(dataset,"Traffic Report - Up Stream","2015-02-09 22:31:27");
    	//增加子标题
    	String title[] = new String[]{"DC MAX:85kb/s","Partition 1 MAX:1332kb/s AVG:10kb/s","Partition 2 MAX:0kb/s"};
    	jFreeChartUtil.addSubTitle(chart, title);
    	//保存图片
    	jFreeChartUtil.saveImage(chart,"");
    	System.out.println("success");
//      
//    	jFreeChartUtil.test1();
    	//1 生成dataset
    	//2 初始化chart
    }
    
    /*
     * 增加子标题
     * */
    public void addSubTitle(  JFreeChart chart,String title[]){
        //摄者chart的子标题
    	if(title.length > 0){
    		for(int i = 0 ; i < title.length ; i++){
    			 chart.addSubtitle(new TextTitle(title[i]));
    		}
    	}
    	
    }
   public Date changeStingToDate(String timeStr) throws ParseException{
	   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	   return  sdf.parse(timeStr);
   }
   public void test1() throws ParseException{
	   String time5 = "2015-05-09 22:31:27";
//	  Date test =  this.changeStingToDate(time5);
//	   System.out.println("test = " + test);
//	   System.out.println("date = " + new Date());
	   
	   
	   JFreeChartUtil chart = new JFreeChartUtil();
	   String name = chart.getXName(time5);
	   System.out.println("name = " + name);
   }
}
 



你可能感兴趣的:(jfreechart 时序图 ,生成图表)