使用jfreechart统计数据,生成折线图(坐标x,y值大小可以自己设置)

需求:一个目录下包含多个txt文件,每个txt文件每行保存一个数据,根据每个txt文件的数据生成一个折线图,y轴为每行的数据,x轴表示第几行。


a.先下载依赖的jar包:jfreechart-1.0.17.jarjcommon-1.0.21.jar 。

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());  
    			}
    		}
    	}
    	 
    	
    }  
}

生成的图,如下:

使用jfreechart统计数据,生成折线图(坐标x,y值大小可以自己设置)_第1张图片



你可能感兴趣的:(使用jfreechart统计数据,生成折线图(坐标x,y值大小可以自己设置))