Use Jfreechart statistics to generate a line chart (coordinates x, y value size can be set by itself)

Source: Internet
Author: User

Requirements: A directory contains multiple TXT files, each TXT file saves one data per line, according to the data of each TXT file to generate a line chart, the y-axis of each row of data, the X-axis represents the first few lines.


A. Download the dependent Jar package first: Jfreechart-1.0.17.jar,jcommon-1.0.21.jar.

B. When you create a new Java project, you rely on the 2 jar packages.

C. Related Jfreechart Introduction:

Org.jfree.chart.ChartFactory: A factory class that gets all kinds of chart types

In this example, using Createxylinechart, the prototype is as follows:

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 in a 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. The implementation is as follows:

Getdata.java processing Data

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 {
	
	//read data from a TXT file 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;
		   First deposit in the list collection
		   while (line = Bw.readline ()) = null) {
		    list.add (line);
		   }
		   Bw.close ();
		  } catch (IOException e) {
			  e.printstacktrace ();
		  }
		 
		  return list;
		 }
	
	Computes the average of the array element 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 {//Save as image file 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);     
	Save As PNG			Chartutilities.writechartaspng (out, chart, weight, height);     
				Save as 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}}}//interface
       
    Name Static String InterfaceName; public static Xyseriescollection CreateDataSet (string fileName) {//the path of the TXT file to be processed by string path = "E:\\inte
    	rfacetest\\gz\\ "+ fileName;
    	Gets the interface name String result = path.substring (0,path.length ()-4);
    	
    	InterfaceName = result.substring (Result.length ());
    	
    	Get the data and put it into the array 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 + "interface, average response time:" + 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.createxyl                Inechart (Response time Statistics,//Chart title "Interface Call Count",//x axis title "Response Time (ms)",                        Y-Axis title CreateDataSet (fileName),//drawing data Set plotorientation.vertical,//drawing direction true, Show Legend TRUE,//using standard generator false);  
        
        Whether to generate hyperlinks//chartframe frame=new chartframe ("Interface Response time Statistics", chart);
    	Sets the caption font Chart.gettitle (). SetFont (New Font ("Arial", Font.Bold, 15)); Chart.getlegend (). Setitemfont (New Font ("Blackbody", Font.Bold, 15));
    	
    	Set legend Category font//Get chart Area object Xyplot plot = (Xyplot) chart.getplot ();
    	Valueaxis Domainaxis=plot.getdomainaxis ();
    	Domainaxis.setticklabelfont (New Font ("Blackbody", Font.Bold, 15));   
    	/*------Set the text on the x-axis coordinates-----------*/Domainaxis.setticklabelfont (new Font ("Blackbody", Font.plain, 11));  
    	
    	/*------Set the title text of the x-axis------------*/Domainaxis.setlabelfont (new Font ("Arial", Font.plain, 12));   
    	Numberaxis Numberaxis = (numberaxis) plot.getrangeaxis ();    
    	/*------Set the text on the y-axis coordinates-----------*/Numberaxis.setticklabelfont (new Font ("Blackbody", Font.plain, 12));
    	
/*------Set the title text of the y-axis------------*/Numberaxis.setlabelfont (new Font ("Arial", Font.plain, 12));
        Terminal display//frame.pack ();  
        
        
    	Frame.setvisible (TRUE);
    	
    	System.out.println (InterfaceName);
        The size of the saved image int weight = 800;
        int height = 600;
        directory where the image is stored 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) {//store. txt directory File File = new file ("E:\\interfacetest\
    	\gz\\ ");
    		if (File.isdirectory ()) {file[] files = file.listfiles ();  
    			for (File myfile:files) {if (Myfile.isfile ()) {Createlinechart (Myfile.getname ()); }
    		}
    	}
    	 
    	
    }  
}

The resulting diagram is as follows:



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.