JFreeChart使用教程(含下载、安装)
- 格式:doc
- 大小:546.00 KB
- 文档页数:22
required libraries can be linked into your Java program. The following image shows the structure of the directories and files :Add complete path of jfreechart-1.0.18.jar and jcommon-1.0.22.jar files to the CLASSPATH as shown below :OS DescriptionWindows Append the Strings “C:\ jfreechart-1.0.18\lib\ jfreechart-1.0.18.jar” and “C:\ jfreechart-1.0.18\lib\ jcommon-1.0.22.jar” to the end of the user variable CLASSPATH Linux Export CLASSPATH=$CLASSPATH: /usr/share/jfreechart-1.0.18/lib/jfreechart-1.0.18.jar: /usr/share/jfreechart-1.0.18/lib/jcommon-1.0.22.jarJFREECHART ARCHITECTUREThis chapter explains basic class level and application level architectures of JFreeChart to give you an idea about how JFreeChart interacts with different classes and how it fits in your Java based application.Class Level ArchitectureThe class level architecture explains how various classes from the library interacts with each other to create various types of charts.Following is the detail of the units used in the above block diagram :Units DescriptionFile The source having user input to be used for creating a dataset inthe file.Database The source having user input to be used for creating a dataset inthe database.Create Dataset Accepts the dataset and stores the dataset into dataset object. General Dataset This type of dataset is mainly used for pie charts.Category Dataset This type of dataset is used for bar chart, line chart,etc.Series Dataset This type of dataset is used for storing series of data and constructline charts.Series Collection Dataset The different categories of series datasets are added to seriescollection dataset. This type of dataset is used for XYLine Charts. Create Chart This is the method which is executed to create final chart.Frame/Image The chart is displayed on a Swing Frame or an image is created. Application Level ArchitectureThe application level architecture explains where JFreeChart library sits inside a Java Application.The client program receives user data and then it make use standard Java and JFreeChart APIs based on requirements to generate the output in the form of either a frame, which can be displayed directly inside the application or independently in the image formats such as JPEG or PNG.JFREECHART - PIE CHARTIn a pie chart, the arc length of each sector is proportional to the quantity it represents. This chapter demonstrates how we can use JFreeChart to create Pie Chart from a given set of business data.Business dataThe following example depicts mobile sale with the help of a pie chart. Following is a list of different mobile brands and their sale unitsperday.S.N.Mobile Brands Sales UNITSperday1Iphone 5S202Samsung Grand203MOTO G404Nokia Lumia10AWT Based ApplicationFollowing is the code to create Pie Chart from the above given information. This code helps you embed a pie chart in any AWT based application.import javax.swing.JPanel;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartPanel;import org.jfree.chart.JFreeChart;import org.jfree.data.general.DefaultPieDataset;import org.jfree.data.general.PieDataset;import org.jfree.ui.ApplicationFrame;import org.jfree.ui.RefineryUtilities;public class PieChart_AWT extends ApplicationFrame{public PieChart_AWT(String title ){super( title );setContentPane(createDemoPanel());}private static PieDataset createDataset(){DefaultPieDataset dataset =new DefaultPieDataset();dataset.setValue("IPhone 5s",new Double(20));dataset.setValue("SamSung Grand",new Double(20));dataset.setValue("MotoG",new Double(40));dataset.setValue("Nokia Lumia",new Double(10));return dataset;}private static JFreeChart createChart(PieDataset dataset ){JFreeChart chart =ChartFactory.createPieChart("Mobile Sales",// chart titledataset,// datatrue,// include legendtrue,false);return chart;}public static JPanel createDemoPanel(){JFreeChart chart = createChart(createDataset());return new ChartPanel( chart );}public static void main(String[] args ){PieChart_AWT demo =new PieChart_AWT("Mobile Sales");demo.setSize(560,367);RefineryUtilities.centerFrameOnScreen( demo );demo.setVisible(true);}}dataset,// datatrue,// include legendtrue,false);int width =640;/* Width of the image */int height =480;/* Height of the image */File pieChart =new File("PieChart.jpeg");ChartUtilities.saveChartAsJPEG( pieChart , chart , width , height );}}Let us keep the above Java code in PieChart.java file, and then compile and run it from command prompt as follows :$javac PieChart.java$java PieChartIf everything is fine , it will compile and run to create JPEG image file named PieChart.jpeg in your current directory.JFREECHART - BAR CHARTThis chapter demonstrates how we can use JFreeChart to create Bar Chart from a given set of business data.A bar chart uses different orientation horizontalorvertical bars to show comparisons in various categories. One axis domainaxis of the chart shows the specific domain being compared, and the other axis rangeaxis represents discrete values.Business DataThe following example depicts various car statistics with the help of a bar chart. Following is a list of car brands along with their different characteristics, which we will show using a bar chart :Car Speed User Rating Millage SafetyFiat 1.0 3.0 5.0 5.oAudi 5.0 6.010.0 4.0Ford 4.0 2.0 3.0 6.0AWT Based ApplicationFollowing is the code to create Bar Chart from the above given information. This code helps you embed a bar chart in any AWT based application.import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartPanel;import org.jfree.chart.JFreeChart;import org.jfree.chart.plot.PlotOrientation;import org.jfree.data.category.CategoryDataset;import org.jfree.data.category.DefaultCategoryDataset;import org.jfree.ui.ApplicationFrame;import org.jfree.ui.RefineryUtilities;public class BarChart_AWT extends ApplicationFrame{public BarChart_AWT(String applicationTitle ,String chartTitle ){super( applicationTitle );JFreeChart barChart =ChartFactory.createBarChart(chartTitle,"Category","Score",createDataset(),PlotOrientation.VERTICAL,true,true,false);ChartPanel chartPanel =new ChartPanel( barChart );chartPanel.setPreferredSize(new java.awt.Dimension(560,367));setContentPane( chartPanel );}private CategoryDataset createDataset(){final String fiat ="FIAT";final String audi ="AUDI";final String ford ="FORD";final String speed ="Speed";final String millage ="Millage";final String userrating ="User Rating";final String safety ="safety";final DefaultCategoryDataset dataset =new DefaultCategoryDataset();dataset.addValue(1.0, fiat , speed );dataset.addValue(3.0, fiat , userrating );dataset.addValue(5.0, fiat , millage );dataset.addValue(5.0, fiat , safety );dataset.addValue(5.0, audi , speed );dataset.addValue(6.0, audi , userrating );dataset.addValue(10.0, audi , millage );dataset.addValue(4.0, audi , safety );dataset.addValue(4.0, ford , speed );dataset.addValue(2.0, ford , userrating );dataset.addValue(3.0, ford , millage );dataset.addValue(6.0, ford , safety );return dataset;}public static void main(String[] args ){BarChart_AWT chart =new BarChart_AWT("Car Usage Statistics","Which car do you like?);chart.pack( );RefineryUtilities.centerFrameOnScreen( chart );chart.setVisible( true );}}Let us keep the above Java code in BarChart_AWT.java file, and then compile and run it from command prompt as follows :$javac BarChar_AWT.java$java BarChart_AWTIf everything is fine , it will compile and run to generate the following Bar Graph :JPEG Image CreationLet us re-write above example to generate a JPEG image from command line. import java.io.*;import org.jfree.chart.ChartFactory;import org.jfree.chart.JFreeChart;import org.jfree.chart.plot.PlotOrientation;import org.jfree.data.category.DefaultCategoryDataset;import org.jfree.chart.ChartUtilities;public class BarChart{public static void main(String[] args )throws Exception{final String fiat ="FIAT";final String audi ="AUDI";final String ford ="FORD";final String speed ="Speed";final String millage ="Millage";final String userrating ="User Rating";final String safety ="safety";final DefaultCategoryDataset dataset =new DefaultCategoryDataset();dataset.addValue(1.0, fiat , speed );dataset.addValue(3.0, fiat , userrating );dataset.addValue(5.0, fiat , millage );dataset.addValue(5.0, fiat , safety );dataset.addValue(5.0, audi , speed );dataset.addValue(6.0, audi , userrating );dataset.addValue(10.0, audi , millage );dataset.addValue(4.0, audi , safety );dataset.addValue(4.0, ford , speed );dataset.addValue(2.0, ford , userrating );dataset.addValue(3.0, ford , millage );dataset.addValue(6.0, ford , safety );JFreeChart barChart =ChartFactory.createBarChart("CAR USAGE STATIStICS","Category","Score",dataset,PlotOrientation.VERTICAL,true,true,false);int width =640;/* Width of the image */int height =480;/* Height of the image */File BarChart=new File("BarChart.jpeg");ChartUtilities.saveChartAsJPEG(BarChart, barChart , width , height );}}Let us keep the above Java code in BarChart.java file, and then compile and run it from command prompt as follows:$javac BarChart.java$java BarChartIf everything is fine , it will compile and run to create JPEG image file named BarChart.jpeg in your current directoryLoading [MathJax]/jax/output/HTML-CSS/jax.js。
Jfreechart图形开发指南廊坊市大华夏神农信息技术有限公司2010年05月修订历史记录目录目录1.引言 (3)2.JFREECHART开发 (3)2.1绘制曲线图 (3)2.2绘制柱状图 (5)2.3绘制三维柱状图 (6)2.4绘制平面饼状图 (7)2.5绘制3D饼状图 (8)2.6绘制时序图 (9)2.7绘制甘特图 (11)3.依赖的JAR包 (13)1.引言JFreeChart是JAVA平台上的一个开放的图表绘制类库。
它完全使用JAVA语言编写,是为applications, applets, servlets 以及JSP等使用所设计。
JFreeChart可生成饼图(pie chart s)、柱状图(bar charts)、散点图(scatter plots)、时序图(time series)、甘特图(G antt charts)等等多种图表,并且可以产生PNG和JPEG格式的输出,还可以与PDF和EX CEL关联。
JFreeChart目前是最好的java图形解决方案,基本能够解决目前的图形方面的需求。
2.jfreechart开发2.1绘制曲线图工具类< LineChart >示例代码:图样:2.2绘制柱状图工具类<BarChart>示例代码:图样:2.3绘制三维柱状图工具类<BarChart>示例代码:图样:2.4绘制平面饼状图工具类<PieChart>示例代码:图样:2.5绘制3D饼状图工具类<PieChart3D>示例代码:图样:2.6绘制时序图工具类< TimeSeriesChart> 示例代码:图样:2.7绘制甘特图工具类< TimeSeriesChart> 示例代码:图样:3.依赖的jar包。
利用JFreeChart生成折线图通过JFreeChart插件,既可以生成普通效果的折线图,也可以生成3D效果的折线图。
如果想生成普通效果的折线图,需要通过工厂类ChartFactory的createLineChart()方法获得JFreeChart类的实例;如果想生成3D效果的折线图,需要通过工厂类ChartFactory的createLineChart3D()方法获得JFreeChart类的实例。
这两个方法的入口参数是完全相同的,各个入口参数的类型及功能请参见14.2.1节的表14.2。
可以分别通过绘图区对象CategoryPlot的getDomainAxis()方法和getRangeAxis()方法,获得横轴对象和纵轴对象,通过得到的轴对象可以设置绘制坐标轴的相关属性,常用方法及实现功能如表14.4所示。
表14.4 设置坐标轴绘制属性的部分通用方法纵轴对象还提供了设置坐标最大值的方法setUpperBound(double max),在默认情况下将最大值控制在能够正常绘制统计图的范围内。
通过java.awt.BasicStroke类可以绘制出各种各样的线段,大体分为实线段和虚线段,可控的绘制条件包括线条的宽度、线段端点的风格、折线段的折点风格、虚线段的绘制风格和虚线段的绘制偏移量,BasicStroke类提供的所有构造方法如表14.5所示。
表14.5 BasicStroke类提供的所有构造方法线段端点的修饰风格有3种,分别由3个常量表示,具体信息如表14.6所示。
表14.6 线段端点修饰风格简介线段折点的修饰风格同样有3种,也由3个常量表示,具体信息如表14.7所示。
表14.7 线段折点修饰风格简介入口参数dash 用来定义虚线,为float 型数组,当dash 数组由偶数个元素组成时,索引值为偶数的元素值代表虚线段的长度,索引值为奇数的元素值代表两个虚线段之间的空白部分的长度,需要注意的是,数组的索引值是从0开始的;当数组中只有一个元素时,例如dash={6},等同于dash={6,6}。
jfreechart用法例子一、饼图:DefaultPieDataset dataset=new DefaultPieDataset();//开始填充数据dataset.setValue("Java", new Double(43.200000000000003D));dataset.setValue("Visual Basic", new Double(10D));dataset.setValue("C/C++", new Double(17.5D));dataset.setValue("PHP", new Double(32.5D));dataset.setValue("Perl", new Double(12.5D));JFreeChart chart=ChartFactory.createPieChart("2D饼型图",dataset,true,true,true);chart.setTitle("统计图");//设置图片标题ChartRenderingInfo info=new ChartRenderingInfo(new StandardEntityCollection());StringimgaeFileName=ServletUtilities.saveChartAsJPEG(chart,300,200, info,session);//设置生成图片,包括图片的大小,长度是300,宽是200session.setAttribute("image_name1",imageFileName;String URL= request.getContextPath() + "/servlet/DisplayChart?filename=" + filename;//Display为org.jfree.chart.servlet.DisplayChartsession.setAttribute("image_url1",URL);显示代码:(以下显示代码不注明了,是一样的,只是session中的属性名不同而已,大家注意区别)" width=300 height=200 border=0 usemap="#<%=session.getAttribute("image_name1") %>">二、3D饼图DefaultPieDataset defaultpiedataset = new DefaultPieDataset();defaultpiedataset.setValue("Java", new Double(43.200000000000003D));defaultpiedataset.setValue("Visual Basic", new Double(10D));defaultpiedataset.setValue("C/C++", new Double(17.5D));defaultpiedataset.setValue("PHP", new Double(32.5D));defaultpiedataset.setValue("Perl", new Double(12.5D));JFreeChart jfreechart = ChartFactory.createPieChart3D("3D 饼图", defaultpiedataset, true, false, false);PiePlot3D pieplot3d = (PiePlot3D)jfreechart.getPlot();String imageFileName2= ServletUtilities.saveChartAsJPEG(jfreechart,300,200,session);session.setAttribute("image_name2",imageFileName2);StringURL=request.getContextPath()+"/servlet/DisplayChart?filename ="+imageFileName2;session.setAttribute("image_url2",URL);三、柱图DefaultCategoryDataset dataset=new DefaultCategoryDataset();//设置数据源dataset.setValue(new Double(43.200000000000003D),"图解","Java" );dataset.setValue( new Double(10D),"图解","Visual Basic");dataset.setValue(new Double(17.5D), "图解","C/C++");dataset.setValue(new Double(32.5D), "图解","PHP");dataset.setValue(new Double(12.5D), "图解","Perl");//添加数据,参数包括名称和数值JFreeChart chart1=ChartFactory.createBarChart3D("柱图","大人物","地盘", dataset,PlotOrientation.VERTICAL,false,false,false);CategoryPlot plot=chart1.getCategoryPlot();//BarRenderer3D renderer1=new BarRenderer3D();final BarRenderer renderer1 = (BarRenderer)plot.getRenderer();renderer1.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());renderer1.setItemLabelsVisible(true);//显示每个柱子上的数据renderer1.setItemMargin(0.1);//设置每个柱子之间的距离plot.setRenderer(renderer1);//让上面对柱子的设置生效StringimageFileName=ServletUtilities.saveChartAsJPEG(chart1,300,20 0,session);//生成图片,包括图片的大小session.setAttribute("image_name3",imageFileName);StringURL=request.getContextPath()+"/servlet/DisplayChart?filename ="+imageFileName;session.setAttribute("image_url3",URL);四、线图DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset();defaultcategorydataset.addValue(212D, "Classes", "JDK 1.0");defaultcategorydataset.addValue(504D, "Classes", "JDK 1.1");defaultcategorydataset.addValue(1520D, "Classes", "SDK 1.2");defaultcategorydataset.addValue(1842D, "Classes", "SDK 1.3");defaultcategorydataset.addValue(2991D, "Classes", "SDK 1.4");JFreeChart jfreechart = ChartFactory.createLineChart("Java Standard Class Library", "线图", "Class Count", defaultcategorydataset, PlotOrientation.VERTICAL, false, true, false);jfreechart.addSubtitle(new TextTitle("Number of Classes By Release"));TextTitle texttitle = new TextTitle("线图");texttitle.setFont(new Font("SansSerif", 0, 10));texttitle.setPosition(RectangleEdge.BOTTOM);texttitle.setHorizontalAlignment(HorizontalAlignment.RIGH T);jfreechart.addSubtitle(texttitle);jfreechart.setBackgroundPaint(Color.white);CategoryPlot categoryplot = (CategoryPlot)jfreechart.getPlot();categoryplot.setBackgroundPaint(Color.lightGray);categoryplot.setRangeGridlinePaint(Color.white);NumberAxis numberaxis = (NumberAxis)categoryplot.getRangeAxis();numberaxis.setStandardTickUnits(NumberAxis.createInteger TickUnits());LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer)categoryplot.getRenderer();lineandshaperenderer.setShapesVisible(true);lineandshaperenderer.setDrawOutlines(true);lineandshaperenderer.setUseFillPaint(true);lineandshaperenderer.setFillPaint(Color.white);String imageFileName4 = ServletUtilities.saveChartAsJPEG(jfreechart,500,500,session);session.setAttribute("image_name4",imageFileName4);StringURL=request.getContextPath()+"/servlet/DisplayChart?filename ="+imageFileName4;session.setAttribute("image_url4",URL);五、时序图TimeSeries timeseries = new TimeSeries("Random Data");Dayday = new Day(1, 1, 1990);double d = 100D;for(int j = 0; j < 4000; j++)try{d = (d + Math.random()) - 0.5D;timeseries.add(day, new Double(d));day = (Day)day.next();}catch(SeriesException seriesexception){System.err.println("Error adding to series");}XYDataset xydataset = new TimeSeriesCollection(timeseries);JFreeChart jfreechart = ChartFactory.createTimeSeriesChart("时序图", "Day", "Value", xydataset, false, false, false);XYPlot xyplot = (XYPlot)jfreechart.getPlot();XYLineAndShapeRenderer xylineandshaperenderer = new XYLineAndShapeRenderer();xylineandshaperenderer.setDefaultShapesVisible(false);xylineandshaperenderer.setSeriesStroke(0, new BasicStroke(0.5F, 1, 1, 5F, new float[] {5F, 10F}, 0.0F));xyplot.setRenderer(xylineandshaperenderer);String imageFileName5 = ServletUtilities.saveChartAsJPEG(jfreechart,500,500,session);session.setAttribute("image_name5",imageFileName5);StringURL=request.getContextPath()+"/servlet/DisplayChart?filename ="+imageFileName5;session.setAttribute("image_url5",URL);。
代码大概三百行吧,不多。
本来连接数据库做是个不错的选择,但是我刚刷了系统木有了又懒得装,从txt输入又感觉太low,最后就作死选择了以前从未尝试过的从Excel 输入,并碰到了各种问题_(:зゝ∠)_比如Cannot get a String value from a numeric cell 的异常错误,卡了我好久,直到无语地发现POI操作Excel时会无视Excel里的单元格设置,自判数据类型,所以还要使用setCellType.(*゜ー゜*)实现步骤(1)我用javax.swing.JFileChooser类来显示文件对话框,让用户选择一个Excel文件。
(2)使用Apache POI API从Excel文件中读取数据,对Employee类进行批量初始化。
(3)实现公司员工收入的相关统计,这里我实现了人数统计、最大/最小工龄查找、最大/最小工资查找、男女比例、平均工资、平均年龄、平均工龄等。
(4)建立Dataset。
将你所想要显示的数据都放到这个库中。
(5)建立JFreeChart对象。
将你的dataset填入到这个对象中。
(6)处理Chart中文显示问题(7)设置各种JFreeChart的属性和效果。
通过它提供的各种方法和接口设置相关的属性。
(8)用JFreeChart绘制图表,然后按照个人的需求进行执行。
(9)写界面,以swing形式输出。
测试截图(1)生成消息对话框,要求用户选择一个Excel文件,单击“确定”(2)生成文件选择器,我打开了存放在D盘BUAA文件夹里的Employee.xls补充说明:这是文件Employee.xls的内容(3)进行相关统计,并通过消息对话框显示统计结果(4)询问用户是否生成统计图,如果点“取消”或“否”,运行完毕;如果点是,系统将生成统计图,以员工为横轴,以年龄、工龄、工资三项数值为纵轴。
图表的显示效果会根据窗口大小自适应,改变横纵轴的比例尺。
下面是窗口最大化的效果程序清单1 2 3 4 5 6 7 8public class Employee {String ID;String name;String sex;double age;double workAge;double sal;9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32public void setID(String ID) {this.ID = ID;}public void setName(String name) { = name;}public void setSex(String sex) {this.sex = sex;}public void setAge(double age) {this.age = age;}public void setWorkAge(double workAge) {this.workAge = workAge;}public void setSal(double sal) {this.sal = sal;}}一共有两个:Employee.Java和EmployeeStatic.javaEmployeeStatic.javaimport java.awt.RenderingHints;import java.io.FileInputStream;import java.util.ArrayList;import java.util.List;import javax.swing.JFileChooser;import javax.swing.JOptionPane;//org.apache.poiimport ermodel.HSSFSheet;import ermodel.HSSFWorkbook;import ermodel.Cell;import ermodel.Row;import ermodel.XSSFSheet;import ermodel.XSSFWorkbook;//org.jfreeimport org.jfree.chart.ChartFactory;import org.jfree.chart.ChartFrame;import org.jfree.chart.JFreeChart;import org.jfree.chart.axis.CategoryAxis;import org.jfree.chart.axis.ValueAxis;import org.jfree.chart.plot.CategoryPlot;import org.jfree.chart.plot.PlotOrientation;import org.jfree.chart.title.TextTitle;import org.jfree.data.category.CategoryDataset;import org.jfree.data.category.DefaultCategoryDataset;import java.awt.Font;public class EmployeeStatics {public static void main(String[] args) {// TODO Auto-generated method stubJOptionPane.showMessageDialog(null,"\n您好,我是智能机器人小紫\n\n" + "很高兴为您提供员工数据统计分析服务\n\n"+ "请选择一个Excel文件 ^_^\n\n","选择Excel文件",RMATION_MESSAGE); ArrayList<Employee> Employees = null;//从Excel文件读取数据try {Employees = ReadFileUsingFileChooser();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}//人数统计int n = Employees.size();//最大最小工资、工龄、工资初始化int maxA = 0;int minA = Integer.MAX_VALUE;int maxWA = 0;int minWA = Integer.MAX_VALUE;int maxS = 0;int minS = Integer.MAX_VALUE;//男女性别人数int M = 0;int FM = 0;double sumS, sumA, sumWA, avgS, avgA, avgWA, MFM; sumS = sumA = sumWA = 0;//遍历实现相关统计for (Employee e : Employees) {if(e.age > maxA)maxA = (int) e.age;if(e.age < minA)minA = (int) e.age;if(e.workAge > maxWA)maxWA = (int) e.workAge;if(e.workAge < minWA)minWA = (int) e.workAge;if(e.sal > maxS)maxS = (int) e.sal;if(e.sal < minS)minS = (int) e.sal;sumS += e.sal;sumA += e.age;sumWA += e.workAge;if (e.sex.equals("男"))M++;if (e.sex.equals("女"))FM++;}//计算平均值avgS = sumS / n;avgA = sumA / n;avgWA = sumWA / n;//计算男女比例MFM = (double) M / FM;JOptionPane.showMessageDialog(null,"员工人数为" + n + ",男女比例为" + MFM + "(男/女)\n"+ "平均年龄为" + avgA + ",平均工龄为" + avgWA + ",平均工资为" + avgS + "\n"+ "最高年龄为" + maxA + ",最低年龄为" + minA + ",最高工龄为" + maxWA + ",最低工龄为" + minWA + "\n"+ "最高工资为" + maxS + "K,最低工资为" + minS + "K\n");int option=JOptionPane.YES_OPTION;option=JOptionPane.showConfirmDialog(null, "是否显示员工数据统计图?");if (option==JOptionPane.YES_OPTION) {CategoryDataset dataset = getDataSet(Employees);//构造chartJFreeChart chart = ChartFactory.createBarChart3D("员工数据统计图", // 图表标题"员工属性", // 目录轴的显示标签--横轴"数值", // 数值轴的显示标签--纵轴dataset, // 数据集PlotOrientation.VERTICAL, // 图表方向:水平、true, // 是否显示图例(对于简单的柱状图必须false, // 是否生成工具false// 是否生成URL链接);//处理chart中文显示问题processChart(chart);//chart 以swing形式输出ChartFrame pieFrame = new ChartFrame("员工数据统计图", chart);pieFrame.pack();pieFrame.setVisible(true);}}public static ArrayList<Employee>ReadFileUsingFileChooser()throws Ex ception {// TODO Auto-generated method stubJFileChooser fileChooser = new JFileChooser();ArrayList temp = new ArrayList();if (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION) {java.io.File file = fileChooser.getSelectedFile();FileInputStream fileIn = new FileInputStream(file);//根据指定的文件输入流导入Excel从而产生Workbook对象HSSFWorkbook wb0 = new HSSFWorkbook(fileIn);//获取Excel文档中的第一个表单HSSFSheet sht0 = wb0.getSheetAt(0);//对Sheet中的每一行进行迭代int r;int rowNum = sht0.getPhysicalNumberOfRows();for (r = 1; r <= rowNum; r++) {Row row = sht0.getRow(r);if (row == null) {break;}//创建实体类Employee info=new Employee();//取出当前行第1个单元格数据,并封装在info实体stuName属性上row.getCell(0).(Cell.);info.setID(row.getCell(0).getStringCellValue());info.setName(row.getCell(1).getStringCellValue());info.setSex(row.getCell(2).getStringCellValue());info.setAge(row.getCell(3).getNumericCellValue());info.setWorkAge(row.getCell(4).getNumericCellValue());info.setSal(row.getCell(5).getNumericCellValue());temp.add(info);}fileIn.close();}else {System.out.println("No file selected");}return temp;}//获取一个演示用的组合数据集对象private static CategoryDatasetgetDataSet(ArrayList<Employee> Employe es) {DefaultCategoryDataset dataset = new DefaultCategoryDataset();for (Employee e : Employees){dataset.addValue(e.workAge, "工龄", );dataset.addValue(e.sal, "工资", );dataset.addValue(e.age, "年龄", );}return dataset;}//解决图表汉字显示问题private static void processChart(JFreeChart chart) {CategoryPlot plot = chart.getCategoryPlot();CategoryAxis domainAxis = plot.getDomainAxis();ValueAxis rAxis = plot.getRangeAxis();chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASI NG,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);TextTitle textTitle = chart.getTitle();textTitle.setFont(new Font("宋体", Font.PLAIN, 20));domainAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 11));domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));rAxis.setTickLabelFont(new Font("sans-serif", Font.PLAIN, 12));rAxis.setLabelFont(new Font("宋体", Font.PLAIN, 12));chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));// renderer.setItemLabelGenerator(newLabelGenerator(0.0));// renderer.setItemLabelFont(newFont("宋体", Font.PLAIN, 12));//renderer.setItemLabelsVisible(true);}}Employee.javapublic class Employee {String ID;String name;String sex;double age;double workAge;double sal;public void setID(String ID) {this.ID = ID;}public void setName(String name) { = name;}public void setSex(String sex) {this.sex = sex;}public void setAge(double age) {this.age = age;}public void setWorkAge(double workAge) { this.workAge = workAge;}public void setSal(double sal) {this.sal = sal;}}。
最近公司使用jfreechart来生成统计图,使用了折线图,饼图等,因为用的1.0.8a版的jfreechart,与1.0.0版本的地方有很多不同,而且图片生成清晰度比老版的高,如下是我做的demo.1.所需包(1) jfreechart-1.0.8a.jar(2) jcommon-1.0.12.jar2.运行环境JDK 1.53.源代码import java.awt.Color;import java.awt.Font;import java.io.File;import java.io.FileOutputStream;import java.text.DecimalFormat;import java.text.NumberFormat;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartUtilities;import org.jfree.chart.JFreeChart;import org.jfree.chart.axis.CategoryAxis;import org.jfree.chart.axis.CategoryLabelPositions;import org.jfree.chart.axis.NumberAxis;import org.jfree.chart.axis.V alueAxis;import bels.StandardCategoryItemLabelGenerator;import bels.StandardPieSectionLabelGenerator;import org.jfree.chart.plot.CategoryPlot;import org.jfree.chart.plot.PiePlot3D;import org.jfree.chart.plot.PlotOrientation;import org.jfree.chart.renderer.category.BarRenderer;import org.jfree.chart.renderer.category.LineAndShapeRenderer;import org.jfree.chart.renderer.category.StackedBarRenderer;import org.jfree.chart.title.TextTitle;import org.jfree.data.category.CategoryDataset;import org.jfree.data.general.DatasetUtilities;import org.jfree.data.general.DefaultPieDataset;import org.jfree.data.general.PieDataset;/*** 实际取色的时候一定要16位的,这样比较准确** @author new*/public class CreateChartServiceImpl{private static final String CHART_PA TH = "E:/test/";public static void main(String[] args){// TODO Auto-generated method stubCreateChartServiceImpl pm = new CreateChartServiceImpl();// 生成饼状图pm.makePieChart();// 生成单组柱状图pm.makeBarChart();// 生成多组柱状图pm.makeBarGroupChart();// 生成堆积柱状图pm.makeStackedBarChart();// 生成折线图pm.makeLineAndShapeChart();}/*** 生成折线图*/public void makeLineAndShapeChart(){double[][] data = new double[][]{{ 672, 766, 223, 540, 126 },{ 325, 521, 210, 340, 106 },{ 332, 256, 523, 240, 526 } };String[] rowKeys ={ "苹果", "梨子", "葡萄" };String[] columnKeys ={ "北京", "上海", "广州", "成都", "深圳" };CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); createTimeXYChar("折线图", "x轴", "y轴", dataset, "lineAndShap.png"); }/*** 生成分组的柱状图*/public void makeBarGroupChart(){double[][] data = new double[][]{ 672, 766, 223, 540, 126 },{ 325, 521, 210, 340, 106 },{ 332, 256, 523, 240, 526 } };String[] rowKeys ={ "苹果", "梨子", "葡萄" };String[] columnKeys ={ "北京", "上海", "广州", "成都", "深圳" };CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); createBarChart(dataset, "x坐标", "y坐标", "柱状图", "barGroup.png");}/*** 生成柱状图*/public void makeBarChart(){double[][] data = new double[][]{{ 672, 766, 223, 540, 126 } };String[] rowKeys ={ "苹果" };String[] columnKeys ={ "北京", "上海", "广州", "成都", "深圳" };CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); createBarChart(dataset, "x坐标", "y坐标", "柱状图", "bar.png");}/*** 生成堆栈柱状图*/public void makeStackedBarChart(){double[][] data = new double[][]{{ 0.21, 0.66, 0.23, 0.40, 0.26 },{ 0.25, 0.21, 0.10, 0.40, 0.16 } };String[] rowKeys ={ "苹果", "梨子" };String[] columnKeys ={ "北京", "上海", "广州", "成都", "深圳" };CategoryDataset dataset = getBarData(data, rowKeys, columnKeys); createStackedBarChart(dataset, "x坐标", "y坐标", "柱状图", "stsckedBar.png"); }/*** 生成饼状图*/public void makePieChart(){double[] data ={ 9, 91 };String[] keys ={ "失败率", "成功率" };createValidityComparePimChar(getDataPieSetByUtil(data, keys), "饼状图", "pie2.png", keys);}// 柱状图,折线图数据集public CategoryDataset getBarData(double[][] data, String[] rowKeys, String[] columnKeys){return DatasetUtilities.createCategoryDataset(rowKeys, columnKeys, data);}// 饼状图数据集public PieDataset getDataPieSetByUtil(double[] data,String[] datadescription){if (data != null && datadescription != null){if (data.length == datadescription.length){DefaultPieDataset dataset = new DefaultPieDataset();for (int i = 0; i < data.length; i++){dataset.setValue(datadescription[i], data[i]);}return dataset;}}return null;/*** 柱状图**@param dataset 数据集* @param xName x轴的说明(如种类,时间等)* @param yName y轴的说明(如速度,时间等)* @param chartTitle 图标题* @param charName 生成图片的名字* @return*/public String createBarChart(CategoryDataset dataset, String xName,String yName, String chartTitle, String charName){JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 图表标题xName, // 目录轴的显示标签yName, // 数值轴的显示标签dataset, // 数据集PlotOrientation.VERTICAL, // 图表方向:水平、垂直true, // 是否显示图例(对于简单的柱状图必须是false)false, // 是否生成工具false // 是否生成URL链接);Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);/** V ALUE_TEXT_ANTIALIAS_OFF表示将文字的抗锯齿关闭,* 使用的关闭抗锯齿后,字体尽量选择12到14号的宋体字,这样文字最清晰好看*///chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.V ALUE_TEXT_ANTIALIAS_OFF);chart.setTextAntiAlias(false);chart.setBackgroundPaint(Color.white);// create plotCategoryPlot plot = chart.getCategoryPlot();// 设置横虚线可见plot.setRangeGridlinesVisible(true);// 虚线色彩plot.setRangeGridlinePaint(Color.gray);// 数据轴精度NumberAxis vn = (NumberAxis) plot.getRangeAxis();// vn.setAutoRangeIncludesZero(true);DecimalFormat df = new DecimalFormat("#0.00");vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式// x轴设置CategoryAxis domainAxis = plot.getDomainAxis();domainAxis.setLabelFont(labelFont);// 轴标题domainAxis.setTickLabelFont(labelFont);// 轴数值// Lable(Math.PI/3.0)度倾斜// domainAxis.setCategoryLabelPositions(CategoryLabelPositions// .createUpRotationLabelPositions(Math.PI / 3.0));domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 横轴上的Lable 是否完整显示// 设置距离图片左端距离domainAxis.setLowerMargin(0.1);// 设置距离图片右端距离domainAxis.setUpperMargin(0.1);// 设置columnKey 是否间隔显示// domainAxis.setSkipCategoryLabelsToFit(true);plot.setDomainAxis(domainAxis);// 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确)plot.setBackgroundPaint(new Color(255, 255, 204));// y轴设置ValueAxis rangeAxis = plot.getRangeAxis();rangeAxis.setLabelFont(labelFont);rangeAxis.setTickLabelFont(labelFont);// 设置最高的一个Item 与图片顶端的距离rangeAxis.setUpperMargin(0.15);// 设置最低的一个Item 与图片底端的距离rangeAxis.setLowerMargin(0.15);plot.setRangeAxis(rangeAxis);BarRenderer renderer = new BarRenderer();// 设置柱子宽度renderer.setMaximumBarWidth(0.05);// 设置柱子高度renderer.setMinimumBarLength(0.2);// 设置柱子边框颜色renderer.setBaseOutlinePaint(Color.BLACK);// 设置柱子边框可见renderer.setDrawBarOutline(true);// // 设置柱的颜色renderer.setSeriesPaint(0, new Color(204, 255, 255));renderer.setSeriesPaint(1, new Color(153, 204, 255));renderer.setSeriesPaint(2, new Color(51, 204, 204));// 设置每个地区所包含的平行柱的之间距离renderer.setItemMargin(0.0);// 显示每个柱的数值,并修改该数值的字体属性renderer.setIncludeBaseInRange(true);renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); renderer.setBaseItemLabelsVisible(true);plot.setRenderer(renderer);// 设置柱的透明度plot.setForegroundAlpha(1.0f);FileOutputStream fos_jpg = null;try{isChartPathExist(CHART_PATH);String chartName = CHART_PA TH + charName;fos_jpg = new FileOutputStream(chartName);ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 500, true, 10);return chartName;}catch (Exception e){e.printStackTrace();return null;}finally{try{fos_jpg.close();}catch (Exception e){e.printStackTrace();}}/*** 横向图** @param dataset 数据集* @param xName x轴的说明(如种类,时间等)* @param yName y轴的说明(如速度,时间等)* @param chartTitle 图标题* @param charName 生成图片的名字* @return*/public String createHorizontalBarChart(CategoryDataset dataset,String xName, String yName, String chartTitle, String charName){JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 图表标题xName, // 目录轴的显示标签yName, // 数值轴的显示标签dataset, // 数据集PlotOrientation.VERTICAL, // 图表方向:水平、垂直true, // 是否显示图例(对于简单的柱状图必须是false)false, // 是否生成工具false // 是否生成URL链接);CategoryPlot plot = chart.getCategoryPlot();// 数据轴精度NumberAxis vn = (NumberAxis) plot.getRangeAxis();//设置刻度必须从0开始// vn.setAutoRangeIncludesZero(true);DecimalFormat df = new DecimalFormat("#0.00");vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式CategoryAxis domainAxis = plot.getDomainAxis();domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的// LableFont labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);domainAxis.setLabelFont(labelFont);// 轴标题domainAxis.setTickLabelFont(labelFont);// 轴数值domainAxis.setMaximumCategoryLabelWidthRatio(0.8f);// 横轴上的Lable 是否完整显示// domainAxis.setVerticalCategoryLabels(false);plot.setDomainAxis(domainAxis);ValueAxis rangeAxis = plot.getRangeAxis();// 设置最高的一个Item 与图片顶端的距离rangeAxis.setUpperMargin(0.15);// 设置最低的一个Item 与图片底端的距离rangeAxis.setLowerMargin(0.15);plot.setRangeAxis(rangeAxis);BarRenderer renderer = new BarRenderer();// 设置柱子宽度renderer.setMaximumBarWidth(0.03);// 设置柱子高度renderer.setMinimumBarLength(30);renderer.setBaseOutlinePaint(Color.BLACK);// 设置柱的颜色renderer.setSeriesPaint(0, Color.GREEN);renderer.setSeriesPaint(1, new Color(0, 0, 255));// 设置每个地区所包含的平行柱的之间距离renderer.setItemMargin(0.5);// 显示每个柱的数值,并修改该数值的字体属性renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); // 设置柱的数值可见renderer.setBaseItemLabelsVisible(true);plot.setRenderer(renderer);// 设置柱的透明度plot.setForegroundAlpha(0.6f);FileOutputStream fos_jpg = null;try{isChartPathExist(CHART_PATH);String chartName = CHART_PA TH + charName;fos_jpg = new FileOutputStream(chartName);ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 500, true, 10);return chartName;}catch (Exception e){e.printStackTrace();return null;}finally{try{fos_jpg.close();}catch (Exception e){e.printStackTrace();}}}/*** 饼状图** @param dataset 数据集* @param chartTitle 图标题* @param charName 生成图的名字* @param pieKeys 分饼的名字集* @return*/public String createValidityComparePimChar(PieDataset dataset,String chartTitle, String charName, String[] pieKeys){JFreeChart chart = ChartFactory.createPieChart3D(chartTitle, // chart// titledataset,// datatrue,// include legendtrue, false);// 使下说明标签字体清晰,去锯齿类似于//chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.V ALUE_TEXT_ANTIALIAS_OFF);的效果chart.setTextAntiAlias(false);// 图片背景色chart.setBackgroundPaint(Color.white);// 设置图标题的字体重新设置titleFont font = new Font("隶书", Font.BOLD, 25);TextTitle title = new TextTitle(chartTitle);title.setFont(font);chart.setTitle(title);PiePlot3D plot = (PiePlot3D) chart.getPlot();// 图片中显示百分比:默认方式// 指定饼图轮廓线的颜色// plot.setBaseSectionOutlinePaint(Color.BLACK);// plot.setBaseSectionPaint(Color.BLACK);// 设置无数据时的信息plot.setNoDataMessage("无对应的数据,请重新查询。
jfreechart画折线图的⽅法JFreeChart 是开放源代码站点 上的⼀个 JAVA 项⽬,它主要⽤来各种各样的图表,这些图表包括:饼图、柱状图 ( 普通柱状图以及堆栈柱状图 )、线图、区域图、分布图、混合图、⽢特图以及⼀些仪表盘等等。
应⽤jfreechart来画图需要两个jar包:jfreechart.jar和jcommon.jar,。
下⾯是⼀个画折线图的例⼦:package yuth.jfree.demo;/*** 使⽤ categoryDataset 数据集创建折线图* 当数据多时,在JPanel中⽆法完全看到横坐标的值,显⽰为省略号。
* 解决⽅法:* ⽅法1、将报表保存为图⽚时,设置图⽚的宽度⾜够⼤(2000或3000),图⽚可以显⽰横坐标值。
* 这种⽅法治标不治本,所以有了第2种⽅法* ⽅法2、设置X轴上的Lable让其45度倾斜。
*/import java.awt.BasicStroke;import java.awt.Color;import java.awt.Dimension;import java.awt.Font;import java.awt.geom.Ellipse2D;import java.io.File;import java.io.IOException;import .URL;import java.text.DecimalFormat;import java.util.Random;import javax.swing.ImageIcon;import javax.swing.JPanel;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartPanel;import org.jfree.chart.ChartUtilities;import org.jfree.chart.JFreeChart;import org.jfree.chart.axis.CategoryAxis;import org.jfree.chart.axis.CategoryLabelPositions;import org.jfree.chart.axis.NumberAxis;import bels.StandardCategoryItemLabelGenerator;import org.jfree.chart.plot.CategoryPlot;import org.jfree.chart.plot.PlotOrientation;import org.jfree.chart.renderer.category.LineAndShapeRenderer;import org.jfree.chart.title.TextTitle;import org.jfree.data.category.CategoryDataset;import org.jfree.data.category.DefaultCategoryDataset;import org.jfree.ui.ApplicationFrame;import org.jfree.ui.HorizontalAlignment;import org.jfree.ui.RectangleEdge;import org.jfree.ui.RectangleInsets;import org.jfree.ui.RefineryUtilities;public class LineChartDemo1 extends ApplicationFrame {private static final long serialVersionUID = -6354350604313079793L;/* synthetic */static Class class$demo$LineChartDemo1;public LineChartDemo1(String string) {super(string);JPanel jpanel = createDemoPanel();jpanel.setPreferredSize(new Dimension(500, 270));setContentPane(jpanel);}/*** 如何区分不同的图例:根据DefaultCategoryDataset.addValue()的第⼆个参数是否相同来区分。
About the T utorialThis tutorial describes various ways to incorporate JFreeChart in Java-based standalone and web-based applications. The tutorial is categorized into various chapters to provide a comprehensive and easy understanding of JFreeChart programming with Java applications.AudienceThis reference has been prepared for beginners to help them understand the basic-to-advanced concepts related to JFreeChart library.PrerequisitesBefore you start practicing the examples given in the tutorial, it is expected that you have a basic understanding of Java programming with JDK1.6 or later versions, Swing, file management and database management in Java.Copyright & Disclaimer© Copyright 2017 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of the contents of this e-book in any manner without written consent of the publisher.We strive to update the contents of our website and tutorials as timely and as precisely as possibly; however, the contents may contain inaccuracies or errors. Tutorials Point (I) provides no guarantee regarding the accuracy, timeliness, or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at **************************T able of ContentsAbout the Tutorial (i)Audience (i)Prerequisites (i)Copyright & Disclaimer (i)Table of Contents .................................................................................................................................... i i 1.JFREECHART ─ OVERVIE W (1)What is JFreeChart? (1)Why JFreeChart? (1)2.JFREECHART ─ INSTALL ATION (2)System Requirements (2)Installing JFreeChart (2)3.JFREECHART ─ ARCHITE CTURE (6)Class Level Architecture (6)Application Level Architecture (7)4.JFREECHART ─ REFEREN CED APIS (8)ChartFactory Class (8)ChartFrame Class (9)ChartPanel Class (10)ChartUtilities Class (10)JFreeChart Class (11)PiePlot Class (12)PiePlot3D Class (12)PlotOrientation Class (13)XYPlot Class (14)XYLineAndShapeRenderer Class (15)XYItemRenderer general datasets (16)PieDataset (16)DefaultPieDataset Class (16)SeriesException Class (17)DefaultCategoryDataset (17)Series Datasets (18)XYDataset (18)XYZDataset (18)XYSeries (18)XYSeriesCollection (19)Default XYZDataset (20)Time Series in JFreeCharts (20)TimeSeriesCollection (21)Second (22)Frames in JFreeCharts (22)ApplicationFrame (23)RefineryUtilities (23)5.JFREECHART ─ PIE CHA RT (24)Business data (24)AWT Based Application (24)JPEG Image Creation (26)6.JFREECHART ─ BAR CHA RT (28)Business Data (28)AWT Based Application (28)7.JFREECHART ─ LINE CH ART (33)Business Data (33)AWT Based Application (33)JPEG Image Creation (35)8.JFREECHART ─ XY CHAR T (37)Business Data (37)AWT Based Application (38)JPEG Image Creation (40)9.JFREECHART ─ 3D PIE/BAR CHART (43)3D Pie chart (43)3D Bar Chart (45)10.JFREECHART ─ BUBBLE CHART (48)Business Data (48)AWT Based Application (48)JPEG Image Creation (51)11.JFREECHART ─ TIMESER IES CHART (54)Business Data (54)AWT Based Application (54)JPEG Image Creation (56)12.JFREECHART ─ FILE IN TERFACE (59)Business Data (59)Chart Generation Based on File (59)13.JFREECHART ─ DATABAS E INTERFACE (62)Business Data (62)Chart Generation Using Database (62)JFreeChart6A chart is a graphical representation of information. There are various tools available, which can be used to create different types of charts. The JFreeChart project was founded in February 2000, by David Gilbert. Today, it is the most widely used charting library among Java developers.This tutorial will help you understand what exactly JFreeChart is, why is it required, and the various ways to create different types of charts within a Java-based application or independently.What is JFreeChart?JfreeChart is an open source library developed in Java. It can be used within Java based applications to create a wide range of charts. By using JFreeChart, we can create all the major type of 2D and 3D charts such as pie chart, bar chart, line chart, XY chart and 3D charts. Why JFreeChart?JFreeChart is open source and 100% free, which permits usage in the commercial applications without any cost. We have enlisted here some more points in favor of why you should use JFreeChart:∙It comes with well documented APIs, which makes it quite easy to understand. ∙ It supports a wide range of chart types such as Pie Chart, Line Chart, Bar Chart, Area Chart and 3D charts.∙ JFreeChart is easy to extend and can be used in both, the client-side, as well as the server-side applications.∙ It supports multiple output formats like PNG, JPEG, PDF, SVG etc.∙It allows extensive customizations of charts. Consider a situation where you are developing an application and you need to show the data in the form of charts, and the data itself is populated dynamically. In such case, displaying the data in the form of charts using JFreeChart programming is very simple.1.JFreeChart 7JFreeChart is popular for its efficient chart creation and user-friendly installation setup. This chapter describes the process of setting up JFreeChart on Windows and Linux. User administration is needed while installing JFreeChart.System RequirementsInstalling JFreeChartTo install JFreeChart, there are three following steps viz …Step 1: Verifying Java InstallationTo verify Java installation, open the console and execute the following java command:2.Once Java installation is done properly, then you should get the following output for both the operating systems:If you do not have Java installed, then install the Java Software Development Kit (SDK) from the link:/technetwork/java/javase/downloads/index.htmlWe assume that you have installed Java 1.7.0_60 version before proceeding for this tutorial.Step 2: Setting JAVA EnvironmentSet the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example,Append Java compiler location to System Path.Verify the command java -version from the command prompted as explained above.Step 3: Installing JFreeChart8Download the latest version of JFreeChart.zip from the link /jfreechart/download/. Unzip the downloaded file at any location from where required libraries can be linked into your Java program. The following image shows the structure of the directories and files:Add complete path of jfreechart-1.0.18.jar and jcommon-1.0.22.jar files to the CLASSPATH as shown below:9JFreeChart10This chapter explains basic class level and application level architectures of JFreeChart to give you an idea about how JFreeChart interacts with different classes and how it fits in your Java based application.Class Level ArchitectureThe class level architecture explains how various classes from the library interact with each other to create various types of charts.Following is the detail of the units used in the above block diagram:3.JFreeChartApplication Level ArchitectureThe application level architecture explains where JFreeChart library sits inside a Java Application.The client program receives user data and then it uses standard Java and JFreeChart APIs based on requirements to generate the output in the form of either a frame, which can be displayed directly inside the application or independently in the image formats such as JPEG or PNG.11JFreeChart12In this chapter, we will discuss about some of the important packages, classes, and methods from JFreeChart library. These packages, classes, and methods are the most frequently used while creating a variety of charts using JFreeChart library.ChartFactory ClassChartFactory is an abstract class under the org.jfree.chart package. It provides a collection of utility methods for generating standard charts. Following is a list of few of the important methods:Class ConstructorClass Methods4.ChartFrame ClassChartFrame class under the org.jfree.chart package, provides all frame related functions and utilities. ChartFrame class inherits functionalities from parent classes such as Frame, Window, Container, and Component classes.13Class ConstructorClass MethodChartPanel ClassChartPanel class from the org.jfree.chart package is used as a swing GUI component for displaying JfreeChart object.Class Constructor14Class MethodChartUtilities ClassCharUtilites class from the org.jfree.chart package provides a collection of utility methods of JFreeCharts including methods for converting charts into image file format such as PNG, JPEG, and creating HTML image maps.Class ConstructorClass Method15JFreeChart ClassJFreeChart class is the core class under the org.jfree.chart package. This class provides JFreeChart method to create bar charts, line charts, pie charts, and xy plots including time series data.Class ConstructorClass MethodPiePlot ClassThis class is a part of org.jfree.chart.plot package and extends Plot class from the same package. This class provides methods to create Pie Plots.Class Constructor16Class MethodPiePlot3D ClassPiePlot3D class is a subclass of PiePlot class under the same package. Hence, this class has the same features as PiePlot class, except it is used to create 3D plots.Class ConstructorClass Method17PlotOrientation ClassThis is a serialized class available in org.jfree.chart.plot package and it is used to show the orientation of a 2D plot. The orientation can either be vertical or horizontal. It sets the orientation of Y-axis. A conventional plot has a vertical Y- axis.Field summaryClass MethodXYPlot ClassThis is a general class available in org.jfree.chart.plot package and it is used for the plotting data in the form of (x,y) pairs. This plot can use data from any other class that implements the XYDataSet Interface. XYPlot makes use of a XYItemRenderer to draw each point on the plot.1819Class ConstructorClass MethodNumberAxis ClassThis class is available in org.jfree.chart.axispackage and it can access the numerical data of any axis. When we set the range of any axis to default, it fits according to the range of the data. But using NumberAxis, class we can set the lower margin and upper margin of domain and range axes.Class ConstructorClass MethodXYLineAndShapeRenderer ClassThis is the class, available under org.jfree.chart.renderer.xy package, which takes care of connecting data points with lines and draws shapes at each data point. This renderer class is designed for use with the XYPlot class.Class ConstructorClass Method20XYItemRenderer general datasetsThis is an interface for rendering the format of a single (x, y) item on a XYPlot. The package is org.Jfree.data.general, which has classes and interfaces to define different types of datasets to construct charts.PieDatasetThis is an interface used as a general purpose dataset, where values are associated with keys. As the name suggests, you can use this dataset to supply data for pie charts. This interface extends KeyedValues and DataSet interfaces. All the methods used for this interface are taken from KeyedValues, Values, and Dataset interfaces.DefaultPieDataset ClassThis is a Default implementation class of a PieDataset interface.Class ConstructorClass Method21SeriesException ClassThis is an exception class. It raises an exception occurred in the time series of data in the dataset. Exceptions are raised on the occurrence of duplicate or invalid data. The time series must not be applied with duplicates and the format must be valid. DefaultCategoryDatasetThis is a default implementation class of CategoryDataset interface.Class ConstructorClass Method22Refer JFreeChart API for more information on various other methods and fields.Series DatasetsThe series dataset is used by XY charts. The package is org.Jfree.data.xy, which contains classes and interfaces belonging to xy charts. The core interface is XYDataset. XYDatasetThis is an interface through which data in the form of (x,y) items can be accessed. As the name suggests, you can use this dataset to serve XY chart. Some of the methods in this interface are taken from SeriesDateset interface.XYZDatasetThis is an interface through which data in the form of (x,y,z) items can be accessed. As the name suggests, you can use this dataset to serve XYZ chart. Some of the methods in this interface are taken from SeriesDateset.XYSeriesThis is a class, which represents a sequence of zero or more data items in the form (x, y). By default, the items in the series are sorted into ascending order by x-value, and duplicate x-values are permitted. Both the sorting and duplicate defaults can be changed in the constructor. Y-values can be denoted as null to represent missing values.Class Constructor23Class MethodThe above method is used in the tutorial example. If you want to learn the remaining methods and fields, please refer JFreeChart API.XYSeriesCollectionXYSeriesCollection class has parent classes like AbstractIntervelDataset, AbstractXYDatset, AbstractSeriesDataset and AbstractDataset. Some of the methods in this class belong to parent classes of this class.Class ConstructorClass Method2425Refer JFreeChart API for the remaining methods and fields.Default XYZDatasetDefaultXYZDataset class have parent classes like AbstractIntervelDataset, AbstractXYDatset, AbstractSeriesDataset, AbstractDataset and AbstractXYZDataset. Some of the methods in this class belong to parent classes of this class.Class ConstructorClass MethodPlease refer JFreeChart API for the remaining methods and fields.Time Series in JFreeChartsThe package is org.jfree.data.time . This package contains classes and interfaces, which are used for the time related data.TimeSeriesThis class represents a sequence of data items in the form of period values, where period is some instance ofRegularTimePeriod abstract class such as Time, Day, Hour, Minute, and Second classes.Class ConstructorClass MethodRefer JFreeChart API for the remaining methods and fields.TimeSeriesCollectionThis is a class used as a collection of time series objects. This class implements the XYDataset interface, as well as it extends IntervelXYDataset interface. This makes it convenient to collect series data objects.Class ConstructorClass Method26Please refer JFreeChart API for the remaining methods and fields.SecondThis class represents a second in a particular day. This class is immutable, which is a requirement for all RegularTimePeriod subclass.Class ConstructorClass Method27Please refer JFreeChart API for the remaining methods and fields.Frames in JFreeChartsThe package is org.jfree.ui. This is the package belongs to JCommons API of JFreeChart. It contains utility classes used for creating frames for pre-configured charts. ApplicationFrameThis is a base class for creating the main frame for simple applications. The frame listens for window closing events, and responds by shutting down the JVM. This is fine for small demo applications. For enterprise applications, you need to use something more robust. The main core methods in this class are taken from Component, Container, Window, Frame, and Jframe classes.Class ConstructorThis class helps to create AWT Frames. This is the reason for why we use this class as super class in this tutorial examples.The methods, which are taken form the parent classes are used for opening a frame, closinga frame, changing the size, changing the background or foreground color, and listeners.28RefineryUtilitiesThis is a class collection of utility methods relating to user interface.Class MethodThe above method is used in the tutorial example. Refer JFreeChart API for remaining methods and fields.29JFreeChartEnd of ebook previewIf you liked what you saw…Buy it from our store @ https://30。
JFreeChart的使用2009-03-08 16:17:32标签:休闲 JFreeChart 职场原创作品,允许转载,转载时请务必以超链接形式标明文章原始出处、作者信息和本声明。
否则将追究法律责任。
/502137/136674JFreeChart是一组功能强大、灵活易用的Java绘图API,使用它可以生成多种通用性的报表,包括柱状图、饼图、曲线图、甘特图等。
它能够用在Swing和Web等中制作自定义的图表或报表,并且得到广泛的应用。
下面我们先来看看JFreeChart 的几个例子,来明白JFreeChart到底是做什么的。
相信大家对JFreeChart有了简单的了解吧?先来看看JFreeChart的下载和环境配置。
JFreeChart是开放源代码的免费软件,下载链接为/sourceforge/jfreechart/jfreechart-1.0.12.zip,当前最新版本为1.0.12。
说明:1)source目录:为jfreechart的源码目录;2)lib目录:为包目录,我们需要关注的包为jfreechart-1.0.12.jar、gnujaxp.jar和jcommon-1.0.15.jar这三个包;3)根目录下的jfreechart-1.0.12-demo.jar是例子程序,大家双击后可看到其中有很多例子的运行结果。
这是我的开发环境:JDK:1.6MyEclipse:7.0 Milestone-1Tomcat:5.5.27在MyEclipse中新建一个项目JFreeChart,将以上三个jar包都放到该项目的类库中,或者干脆把lib目录下所有jar包都导入,这样更直接一些。
并且在WebRoot\WEB-INF\web.xml文件中增加如下配置:<servlet><servlet-name>DisplayChart</servlet-name><servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class> </servlet><servlet-mapping><servlet-name>DisplayChart</servlet-name><url-pattern>/DisplayChart</url-pattern></servlet-mapping>接下来先做一个例子,来测试该项目内JFreeChart是否可用。
用JFreeChart增强JSP报表的用户体验 JFreeChart是一组功能强大、灵活易用的Java绘图API,使用它可以生成多种通用性的报表,包括柱状图、饼图、曲线图、甘特图等。它能够用在Swing和Web等中制作自定义的图表或报表,并且得到广泛的应用。本文将通过引领读者学习在JFreeChart中饼图、柱状图和曲线图的进阶应用,来达到熟练使用JFreeChart的目的。
一. 下载与环境配置 1. 下载JFreeChart JFreeChart是开放源代码的免费软件,但是它的支持文档需要付费才能得到。其下载地址为:http://sourceforge.net/project/showfiles.php?group_id=15494,当前最新版本为1.0.6。笔者下载的是1.0.6最新版。
说明:1)source目录:为jfreechart的源码目录; 2)lib目录:为包目录,我们需要关注的包为jfreechart-1.0.6.jar、gnujaxp.jar和jcommon-1.0.10.jar这三个包;
3)根目录下的jfreechart-1.0.6-demo.jar是例子程序,大家双击后可看到其中有很多例子的运行结果。
2. 环境配置 笔者的开发环境如下: JDK:1.5 MyEclipse:5.1.1 GA Tomcat:5.5.28 为了后续的“用JFreeChart创建基于Web的图表”的一个例子的展示,我们在MyEclipse中创建一个名为jfreechart的Web工程。将下载的JFreeChart1.0.6下lib目录下的jar包拷贝到WebRoot/WEB-INF/lib目录下。另外还需要在web.xml文件中增加如下配置:
DisplayChart org.jfree.chart.servlet.DisplayChart DisplayChart /DisplayChart
二. 柱状图 在WebRoot目录下建立bar目录,用来存放柱状图的各个例子。首先在该目录下建立一个sample1.jsp文件,让我们来看一个简单的柱状图的例子,修改后的sample1.jsp的内容如下所示:
<%@ page contentType="text/html;charset=GBK"%> <%@ page import="org.jfree.chart.ChartFactory, org.jfree.chart.JFre
eChart, org.jfree.chart.plot.PlotOrientation, org.jfree.chart.se
rvlet.ServletUtilities, org.jfree.data.category.DefaultCategoryDataset"%> <%
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(610, "广州", "猪肉");
dataset.addValue(220, "广州", "牛肉");
dataset.addValue(530, "广州", "鸡肉");
dataset.addValue(340, "广州", "鱼肉");
JFreeChart chart = ChartFactory.createBarChart3D("肉类销量统计图",
"肉类",
"销量",
dataset,
PlotOrientation.VERTICAL,
false,
false,
false);
String filename = ServletUtilities.saveChartAsPNG(chart, 500, 300, null, session);
String graphURL = request.getContextPath() + "/DisplayChart?filename=" + filename;
%>
在浏览器中输入地址:http://localhost:8080/jfreechart/bar/sample1.jsp,可看到如下柱状图: 上面的这个柱状图比较简单,稍显单调,在有些情况下,我们需要用不同颜色来表示不同的种类,或者在种类上标上具体数值,亦或需要加上3D水晶效果。下面让我们来做更深一步的探讨。接下来让我们看一个用不同颜色来表示不通种类的例子。在WebRoot的bar目录下新建sample2.jsp页面,将其代码修改如下:
<%@ page contentType="text/html;charset=GBK"%>
<%@ page import="org.jfree.chart.ChartFactory,
org.jfree.chart.JFreeChart,
org.jfree.chart.plot.PlotOrientation,
org.jfree.chart.servlet.ServletUtilities,
org.jfree.data.category.CategoryDataset,
org.jfree.data.general.DatasetUtilities"%>
<%
double[][] data = newdouble[][] {{1310}, {720}, {1130}, {440}};
String[] rowKeys = {"猪肉", "牛肉","鸡肉", "鱼肉"};
String[] columnKeys = {""};
CategoryDataset dataset = DatasetUtilities.createCategoryDataset(rowKeys, columnK
eys, data);
JFreeChart chart = ChartFactory.createBarChart3D("广州肉类销量统计图", "肉类",
"销量",
dataset,
PlotOrientation.VERTICAL,
true,
false,
false);
String filename = ServletUtilities.saveChartAsPNG(chart, 500, 300, null, session);
String graphURL = request.getContextPath() + "/DisplayChart?filename=" + filename;
%>
该页面的运行效果如下图所示:
对比该例与前例,可看出createBarChart3D的倒数第三个参数修改成了true,该参数可用来显示下方的:。上两例我们显示的只是一个城市的肉类销量,有时候我们有对比显示多个城市的不同肉类,只要将上例稍作修改即可。例如要在图中表示广州、深圳、东莞、佛山四个城市的四个肉类的销售情况,只需要将如下三句稍做修改:
double[][] data = newdouble[][] {{1310}, {720}, {1130}, {440}}; String[] rowKeys = {"猪肉", "牛肉","鸡肉", "鱼肉"}; String[] columnKeys = {""}; 例如修改成: double[][] data = newdouble[][] {{1310, 1220, 1110, 1000}, {720, 700, 680, 640}, {1130, 1020, 980, 800}, {440, 400, 360, 300}}; String[] rowKeys = {"猪肉", "牛肉","鸡肉", "鱼肉"}; String[] columnKeys = {"广州", "深圳", "东莞", "佛山"};
在运行该jsp页面,可看到如下界面:
在上述几例中,在某个柱子上都没有显示相应的数值,下面让我们为每个柱子都加上它的数值,我们新建一个sample4.jsp页面,其内容如下:
<%@ page contentType="text/html;charset=GBK"%> <%@ page import="org.jfree.chart.ChartFactory, org.jfree.chart.JFreeChar
t, org.jfree.chart.plot.PlotOrientation, org.jfree.chart.servlet.ServletUtilities, or
g.jfree.data.category.CategoryDataset,
org.jfree.data.general.DatasetUtilities,