1. 程式人生 > >使用jfreechart統計資料,生成折線圖(座標x,y值大小可以自己設定)

使用jfreechart統計資料,生成折線圖(座標x,y值大小可以自己設定)

需求:一個目錄下包含多個txt檔案,每個txt檔案每行儲存一個數據,根據每個txt檔案的資料生成一個折線圖,y軸為每行的資料,x軸表示第幾行。

b.建立新的java工程時,依賴這2個jar包。

c.相關jfreechart介紹:

org.jfree.chart.ChartFactory :得到各種型別chart的工廠類

本例中使用createXYLineChart,原型如下:

public static JFreeChart createXYLineChart(java.lang.String title,
                                           java.lang.String xAxisLabel,
                                           java.lang.String yAxisLabel,
                                           
XYDataset
 dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls)
Creates a line chart (based on an 
XYDataset
) with default settings.
Parameters:
title - the chart title (null permitted).
xAxisLabel - a label for the X-axis (null permitted).
yAxisLabel - a label for the Y-axis (null permitted).
dataset - the dataset for the chart (null permitted).
orientation - the plot orientation (horizontal or vertical) (null
 NOT permitted).
legend - a flag specifying whether or not a legend is required.
tooltips - configure chart to generate tool tips?
urls - configure chart to generate URLs?
Returns:
The chart.
實現如下:

GetData.java   處理資料

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GetData {
	
	//從一個txt檔案中讀取資料
	public static List writeToData(String path) {
		  File file = new File(path);
		  List list = new ArrayList();
		  
		  try {
		   BufferedReader bw = new BufferedReader(new FileReader(file));
		   String line = null;
		   //先存入list集合中
		   while((line = bw.readLine()) != null){
		    list.add(line);
		   }
		   bw.close();
		  } catch (IOException e) {
			  e.printStackTrace();
		  }
		 
		  return list;
		 }
	
	//求陣列元素的平均值
    public static double average(double table[]) {

    	double sum=0.0;

    	for (int i=0;i<table.length;i++) {
    		sum += table[i];
    	}
    	return sum / table.length;

    }
    
}

LineChart.java

import java.awt.Font;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.jfree.chart.ChartFactory;  
import org.jfree.chart.ChartFrame;  
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;  
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.PlotOrientation;  
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYSeries;  
import org.jfree.data.xy.XYSeriesCollection;  


public class LineChart {  
 
	// 儲存為影象檔案     
	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, weight, height);     
				//儲存為JPEG     
				//ChartUtilities.writeChartAsJPEG(out, chart, weight, height);     
				out.flush();     
				} catch (FileNotFoundException e) {     
					e.printStackTrace();     
				} catch (IOException e) {     
					e.printStackTrace();     
				} finally {     
					if (out != null) {     
						try {     
							out.close();     
							} catch (IOException e) {     
								// do nothing     
							}     
					}     
				}     
    }     
	
   
    
	//介面名
    static String interfaceName;
       
    public static XYSeriesCollection createDataSet(String fileName) {  
    	
    	//要處理的txt檔案的路徑
    	String path = "e:\\interfaceTest\\gz\\" + fileName;
    	//獲取介面名
    	String result = path.substring(0,path.length()-4);
    	interfaceName = result.substring(20, result.length());
    	
    	//獲取資料,放到陣列中
    	List list = GetData.writeToData(path);
    	
    	double[] nums = new double[list.size()];
    	
    	
		for(int k=0; k < list.size(); k++){
			String s = (String) list.get(k);
			nums[k] = Double.parseDouble(s);
		}
    	
		
		  
		double ave = GetData.average(nums);
		
		System.out.println("ave: " + ave);
    	
    	
        XYSeriesCollection seriesCollection = new XYSeriesCollection();  
        XYSeries series1 = new XYSeries(interfaceName + "介面,平均響應時間:" + ave + "ms");  
        
      
        for(int i=0; i < list.size(); i++){
 		   series1.add(i, nums[i]);
 		  }
        

        seriesCollection.addSeries(series1);  
        
        return seriesCollection;  
    }  
  
    public static void createLineChart(String fileName) {  
    	
        JFreeChart chart = ChartFactory.createXYLineChart("響應時間統計",           //圖表標題
        				"介面呼叫次數",                   //X軸標題
        				"響應時間(毫秒)",                //Y軸標題
        				createDataSet(fileName),     //繪圖資料集
        				PlotOrientation.VERTICAL,    //繪製方向
        				true,                        //顯示圖例
        				true,                        //採用標準生成器
        				false);                      //是否生成超連結
      
        //ChartFrame frame=new ChartFrame("介面響應時間統計",chart);  
        
        //設定標題字型
    	chart.getTitle().setFont(new Font("宋體", Font.BOLD, 15));
    	chart.getLegend().setItemFont(new Font("黑體", Font.BOLD, 15)); // 設定圖例類別字型
    	//獲取圖表區域物件
    	XYPlot plot = (XYPlot) chart.getPlot();
    	
    	ValueAxis domainAxis=plot.getDomainAxis();
    	domainAxis.setTickLabelFont(new Font("黑體", Font.BOLD, 15));
    	/*------設定X軸座標上的文字-----------*/ 
    	domainAxis.setTickLabelFont(new Font("黑體", Font.PLAIN, 11));   
    	/*------設定X軸的標題文字------------*/ 
    	domainAxis.setLabelFont(new Font("宋體", Font.PLAIN, 12));  
    	
    	NumberAxis numberaxis = (NumberAxis) plot.getRangeAxis();   
    	/*------設定Y軸座標上的文字-----------*/ 
    	numberaxis.setTickLabelFont(new Font("黑體", Font.PLAIN, 12));    
    	/*------設定Y軸的標題文字------------*/ 
    	numberaxis.setLabelFont(new Font("宋體", Font.PLAIN, 12));
    	

        //終端顯示
    	//frame.pack();  
    	//frame.setVisible(true);  
        
        
    	System.out.println(interfaceName);
    	
    	//儲存影象的大小
        int weight = 800;
        int height = 600;
        //存放影象的目錄
        String outputPath = "e:\\interfaceTest\\imgs\\" + interfaceName + ".png";
        //String outputPath = "d:\\interface\\imgs\\" + interfaceName + ".png";
        LineChart.saveAsFile(chart, outputPath, weight, height);
    }  
    
    
    public static void main(String[] args) { 
    	//存放.txt的目錄
    	File file = new File("e:\\interfaceTest\\gz\\");
    	if(file.isDirectory())
    	{
    		File[] files = file.listFiles();
    		for(File myFile:files)
    		{
    			if(myFile.isFile())
    			{
    				createLineChart(myFile.getName());  
    			}
    		}
    	}
    	 
    	
    }  
}

生成的圖,如下: