JFreeChart与专题地图
- 格式:ppt
- 大小:1006.50 KB
- 文档页数:67
JFreeChart支持的图表类型总结JFreeChart类:void setAntiAlias(boolean flag) 字体模糊边界void setBackgroundImage(Image image) 背景图片void setBackgroundImageAlignment(int alignment) 背景图片对齐方式(参数常量在org.jfree.ui.Align类中定义)void setBackgroundImageAlpha(float alpha) 背景图片透明度(0.0~1.0)void setBackgroundPaint(Paint paint) 背景色void setBorderPaint(Paint paint) 边界线条颜色void setBorderStroke(Stroke stroke) 边界线条笔触void setBorderVisible(boolean visible) 边界线条是否可见-----------------------------------------------------------------------------------------------------------TextTitle类:void setFont(Font font) 标题字体void setPaint(Paint paint) 标题字体颜色void setText(String text) 标题内容-----------------------------------------------------------------------------------------------------------StandardLegend(Legend)类:void setBackgroundPaint(Paint paint) 图示背景色void setTitle(String title) 图示标题内容void setTitleFont(Font font) 图示标题字体void setBoundingBoxArcWidth(int arcWidth) 图示边界圆角宽void setBoundingBoxArcHeight(int arcHeight) 图示边界圆角高void setOutlinePaint(Paint paint) 图示边界线条颜色void setOutlineStroke(Stroke stroke) 图示边界线条笔触void setDisplaySeriesLines(boolean flag) 图示项是否显示横线(折线图有效)void setDisplaySeriesShapes(boolean flag) 图示项是否显示形状(折线图有效)void setItemFont(Font font) 图示项字体void setItemPaint(Paint paint) 图示项字体颜色void setAnchor(int anchor) 图示在图表中的显示位置(参数常量在Legend类中定义)-----------------------------------------------------------------------------------------------------------Axis类:void setVisible(boolean flag) 坐标轴是否可见void setAxisLinePaint(Paint paint) 坐标轴线条颜色(3D轴无效)void setAxisLineStroke(Stroke stroke) 坐标轴线条笔触(3D轴无效)void setAxisLineVisible(boolean visible) 坐标轴线条是否可见(3D轴无效)void setFixedDimension(double dimension) (用于复合表中对多坐标轴的设置)void setLabel(String label) 坐标轴标题void setLabelFont(Font font) 坐标轴标题字体void setLabelPaint(Paint paint) 坐标轴标题颜色void setLabelAngle(double angle)` 坐标轴标题旋转角度(纵坐标可以旋转)void setTickLabelFont(Font font) 坐标轴标尺值字体void setTickLabelPaint(Paint paint) 坐标轴标尺值颜色void setTickLabelsVisible(boolean flag) 坐标轴标尺值是否显示void setTickMarkPaint(Paint paint) 坐标轴标尺颜色void setTickMarkStroke(Stroke stroke) 坐标轴标尺笔触void setTickMarksVisible(boolean flag) 坐标轴标尺是否显示ValueAxis(Axis)类:void setAutoRange(boolean auto) 自动设置数据轴数据范围void setAutoRangeMinimumSize(double size) 自动设置数据轴数据范围时数据范围的最小跨度void setAutoTickUnitSelection(boolean flag) 数据轴的数据标签是否自动确定(默认为true)void setFixedAutoRange(double length) 数据轴固定数据范围(设置100的话就是显示MAXVALUE到MAXVALUE-100那段数据范围)void setInverted(boolean flag) 数据轴是否反向(默认为false)void setLowerMargin(double margin) 数据轴下(左)边距void setUpperMargin(double margin) 数据轴上(右)边距void setLowerBound(double min) 数据轴上的显示最小值void setUpperBound(double max) 数据轴上的显示最大值void setPositiveArrowVisible(boolean visible) 是否显示正向箭头(3D轴无效)void setNegativeArrowVisible(boolean visible) 是否显示反向箭头(3D轴无效)void setVerticalTickLabels(boolean flag) 数据轴数据标签是否旋转到垂直void setStandardTickUnits(TickUnitSource source) 数据轴的数据标签(可以只显示整数标签,需要将AutoTickUnitSelection设false)NumberAxis(ValueAxis)类:void setAutoRangeIncludesZero(boolean flag) 是否强制在自动选择的数据范围中包含0void setAutoRangeStickyZero(boolean flag) 是否强制在整个数据轴中包含0,即使0不在数据范围中void setNumberFormatOverride(NumberFormat formatter) 数据轴数据标签的显示格式void setTickUnit(NumberTickUnit unit) 数据轴的数据标签(需要将AutoTickUnitSelection设false)DateAxis(ValueAxis)类:void setMaximumDate(Date maximumDate) 日期轴上的最小日期void setMinimumDate(Date minimumDate) 日期轴上的最大日期void setRange(Date lower,Date upper) 日期轴范围void setDateFormatOverride(DateFormat formatter) 日期轴日期标签的显示格式void setTickUnit(DateTickUnit unit) 日期轴的日期标签(需要将AutoTickUnitSelection设false)void setTickMarkPosition(DateTickMarkPosition position) 日期标签位置(参数常量在org.jfree.chart.axis.DateTickMarkPosition类中定义)CategoryAxis(Axis)类:void setCategoryMargin(double margin) 分类轴边距void setLowerMargin(double margin) 分类轴下(左)边距void setUpperMargin(double margin) 分类轴上(右)边距void setVerticalCategoryLabels(boolean flag) 分类轴标题是否旋转到垂直void setMaxCategoryLabelWidthRatio(float ratio) 分类轴分类标签的最大宽度-----------------------------------------------------------------------------------------------------------Plot类:void setBackgroundImage(Image image) 数据区的背景图片void setBackgroundImageAlignment(int alignment) 数据区的背景图片对齐方式(参数常量在org.jfree.ui.Align类中定义)void setBackgroundPaint(Paint paint) 数据区的背景图片背景色void setBackgroundAlpha(float alpha) 数据区的背景透明度(0.0~1.0)void setForegroundAlpha(float alpha) 数据区的前景透明度(0.0~1.0)void setDataAreaRatio(double ratio) 数据区占整个图表区的百分比void setOutLinePaint(Paint paint) 数据区的边界线条颜色void setOutLineStroke(Stroke stroke) 数据区的边界线条笔触void setNoDataMessage(String message) 没有数据时显示的消息void setNoDataMessageFont(Font font) 没有数据时显示的消息字体void setNoDataMessagePaint(Paint paint) 没有数据时显示的消息颜色CategoryPlot(Plot)类:void setDataset(CategoryDataset dataset) 数据区的2维数据表void setColumnRenderingOrder(SortOrder order) 数据分类的排序方式void setAxisOffset(Spacer offset) 坐标轴到数据区的间距void setOrientation(PlotOrientation orientation) 数据区的方向(PlotOrientation.HORIZONTAL或PlotOrientation.VERTICAL)void setDomainAxis(CategoryAxis axis) 数据区的分类轴void setDomainAxisLocation(AxisLocation location) 分类轴的位置(参数常量在org.jfree.chart.axis.AxisLocation类中定义)void setDomainGridlinesVisible(boolean visible) 分类轴网格是否可见void setDomainGridlinePaint(Paint paint) 分类轴网格线条颜色void setDomainGridlineStroke(Stroke stroke) 分类轴网格线条笔触void setRangeAxis(ValueAxis axis) 数据区的数据轴void setRangeAxisLocation(AxisLocation location) 数据轴的位置(参数常量在org.jfree.chart.axis.AxisLocation类中定义)void setRangeGridlinesVisible(boolean visible) 数据轴网格是否可见void setRangeGridlinePaint(Paint paint) 数据轴网格线条颜色void setRangeGridlineStroke(Stroke stroke) 数据轴网格线条笔触void setRenderer(CategoryItemRenderer renderer) 数据区的表示者(详见Renderer组)void addAnnotation(CategoryAnnotation annotation) 给数据区加一个注释void addRangeMarker(Marker marker,Layer layer) 给数据区加一个数值范围区域PiePlot(Plot)类:void setDataset(PieDataset dataset) 数据区的1维数据表void setIgnoreNullValues(boolean flag) 忽略无值的分类void setCircular(boolean flag) 饼图是否一定是正圆void setStartAngle(double angle) 饼图的初始角度void setDirection(Rotation direction) 饼图的旋转方向void setExplodePercent(int section,double percent) 抽取的那块(1维数据表的分类下标)以及抽取出来的距离(0.0~1.0),3D饼图无效void setLabelBackgroundPaint(Paint paint) 分类标签的底色void setLabelFont(Font font) 分类标签的字体void setLabelPaint(Paint paint) 分类标签的字体颜色void setLabelLinkMargin(double margin) 分类标签与图的连接线边距void setLabelLinkPaint(Paint paint) 分类标签与图的连接线颜色void setLabelLinkStroke(Stroke stroke) 分类标签与图的连接线笔触void setLabelOutlinePaint(Paint paint) 分类标签边框颜色void setLabelOutlineStroke(Paint paint) 分类标签边框笔触void setLabelShadowPaint(Paint paint) 分类标签阴影颜色void setMaximumLabelWidth(double width) 分类标签的最大长度(0.0~1.0)void setPieIndex(int index) 饼图的索引(复合饼图中用到)void setSectionOutlinePaint(int section,Paint paint) 指定分类饼的边框颜色void setSectionOutlineStroke(int section,Stroke stroke) 指定分类饼的边框笔触void setSectionPaint(int section,Paint paint) 指定分类饼的颜色void setShadowPaint(Paint paint) 饼图的阴影颜色void setShadowXOffset(double offset) 饼图的阴影相对图的水平偏移void setShadowYOffset(double offset) 饼图的阴影相对图的垂直偏移void setLabelGenerator(PieSectionLabelGenerator generator) 分类标签的格式,设置成null则整个标签包括连接线都不显示void setToolTipGenerator(PieToolTipGenerator generator) MAP中鼠标移上的显示格式void setURLGenerator(PieURLGenerator generator) MAP中钻取链接格式PiePlot3D(PiePlot)类:void setDepthFactor(double factor) 3D饼图的Z轴高度(0.0~1.0)MultiplePiePlot(Plot)类:void setLimit(double limit) 每个饼图之间的数据关联(详细比较复杂)void setPieChart(JFreeChart pieChart) 每个饼图的显示方式(见JFreeChart类个PiePlot类)-----------------------------------------------------------------------------------------------------------AbstractRenderer类:void setItemLabelAnchorOffset(double offset) 数据标签的与数据点的偏移void setItemLabelsVisible(boolean visible) 数据标签是否可见void setItemLabelFont(Font font) 数据标签的字体void setItemLabelPaint(Paint paint) 数据标签的字体颜色void setItemLabelPosition(ItemLabelPosition position) 数据标签位置void setPositiveItemLabelPosition(ItemLabelPosition position) 正数标签位置void setNegativeItemLabelPosition(ItemLabelPosition position) 负数标签位置void setOutLinePaint(Paint paint) 图形边框的线条颜色void setOutLineStroke(Stroke stroke) 图形边框的线条笔触void setPaint(Paint paint) 所有分类图形的颜色void setShape(Shape shape) 所有分类图形的形状(如折线图的点)void setStroke(Stroke stroke) 所有分类图形的笔触(如折线图的线)void setSeriesItemLabelsVisible(int series,boolean visible) 指定分类的数据标签是否可见void setSeriesItemLabelFont(int series,Font font) 指定分类的数据标签的字体void setSeriesItemLabelPaint(int series,Paint paint) 指定分类的数据标签的字体颜色void setSeriesItemLabelPosition(int series,ItemLabelPosition position) 数据标签位置void setSeriesPositiveItemLabelPosition(int series,ItemLabelPosition position) 正数标签位置void setSeriesNegativeItemLabelPosition(int series,ItemLabelPosition position) 负数标签位置void setSeriesOutLinePaint(int series,Paint paint) 指定分类的图形边框的线条颜色void setSeriesOutLineStroke(int series,Stroke stroke) 指定分类的图形边框的线条笔触void setSeriesPaint(int series,Paint paint) 指定分类图形的颜色void setSeriesShape(int series,Shape shape) 指定分类图形的形状(如折线图的点)void setSeriesStroke(int series,Stroke stroke) 指定分类图形的笔触(如折线图的线)AbstractCategoryItemRenderer(AbstractRenderer)类:void setLabelGenerator(CategoryLabelGenerator generator) 数据标签的格式void setToolTipGenerator(CategoryToolTipGenerator generator) MAP中鼠标移上的显示格式void setItemURLGenerator(CategoryURLGenerator generator) MAP中钻取链接格式void setSeriesLabelGenerator(int series,CategoryLabelGenerator generator) 指定分类的数据标签的格式void setSeriesToolTipGenerator(int series,CategoryToolTipGenerator generator) 指定分类的MAP中鼠标移上的显示格式void setSeriesItemURLGenerator(int series,CategoryURLGenerator generator) 指定分类的MAP中钻取链接格式BarRenderer(AbstractCategoryItemRenderer)类:void setDrawBarOutline(boolean draw) 是否画图形边框void setItemMargin(double percent) 每个BAR之间的间隔void setMaxBarWidth(double percent) 每个BAR的最大宽度void setMinimumBarLength(double min) 最短的BAR长度,避免数值太小而显示不出void setPositiveItemLabelPositionFallback(ItemLabelPosition position) 无法在BAR中显示的正数标签位置void setNegativeItemLabelPositionFallback(ItemLabelPosition position) 无法在BAR中显示的负数标签位置BarRenderer3D(BarRenderer)类:void setWallPaint(Paint paint) 3D坐标轴的墙体颜色StackedBarRenderer(BarRenderer)类:没有特殊的设置StackedBarRenderer3D(BarRenderer3D)类:没有特殊的设置GroupedStackedBarRenderer(StackedBarRenderer)类:void setSeriesToGroupMap(KeyToGroupMap map) 将分类自由的映射成若干个组(KeyToGroupMap.mapKeyToGroup(series,group))LayeredBarRenderer(BarRenderer)类:void setSeriesBarWidth(int series,double width) 设定每个分类的宽度(注意设置不要使某分类被覆盖)WaterfallBarRenderer(BarRenderer)类:void setFirstBarPaint(Paint paint) 第一个柱图的颜色void setLastBarPaint(Paint paint) 最后一个柱图的颜色void setPositiveBarPaint(Paint paint) 正值柱图的颜色void setNegativeBarPaint(Paint paint) 负值柱图的颜色IntervalBarRenderer(BarRenderer)类:需要传IntervalCategoryDataset作为数据源GanttBarRenderer(IntervalBarRenderer)类:void setCompletePaint(Paint paint) 完成进度颜色void setIncompletePaint(Paint paint) 未完成进度颜色void setStartPercent(double percent) 设置进度条在整条中的起始位置(0.0~1.0)void setEndPercent(double percent) 设置进度条在整条中的结束位置(0.0~1.0)StatisticBarRenderer(BarRenderer)类:需要传StatisticCategoryDataset作为数据源LineAndShapeRenderer(AbstractCategoryItemRenderer)类:void setDrawLines(boolean draw) 是否折线的数据点之间用线连void setDrawShapes(boolean draw) 是否折线的数据点根据分类使用不同的形状void setShapesFilled(boolean filled) 所有分类是否填充数据点图形void setSeriesShapesFilled(int series,boolean filled) 指定分类是否填充数据点图形void setUseFillPaintForShapeOutline(boolean use) 指定是否填充数据点的Paint也被用于画数据点形状的边框LevelRenderer(AbstractCategoryItemRenderer)类:void setItemMargin(double percent) 每个分类之间的间隔void setMaxItemWidth(double percent) 每个分类的最大宽度CategoryStepRenderer(AbstractCategoryItemRenderer)类:void setStagger(boolean shouldStagger) 不同分类的图是否交错MinMaxCategoryRenderer(AbstractCategoryItemRenderer)类:void setDrawLines(boolean drawLines) 是否在每个分类线间画连接线void setGroupPaint(Paint groupPaint) 一组图形连接线的颜色void setGroupStroke(Stroke groupStroke) 一组图形连接线的笔触void setMaxIcon(Icon maxIcon) 最大值的ICONvoid setMinIcon(Icon minIcon) 最小值的ICONvoid setObjectIcon(Icon objectIcon) 所有值的ICONAreaRender(AbstractCategoryItemRenderer)类:没有特殊的设置StackedAreaRender(AreaRender)类:没有特殊的设置。
JFreechart完整柱状图import class AttendanceMain{p ublic static void main(String[] args) throws IOException{double[][] data = new double[][]{{100,96,98,95,99,100,92,93,91,94,96},{97,96,98,95,99,100,92,93,91,94,96},{97,96,98,95,99,100,92,93,91,94,96},{97,96,98,95,99,100,92,93,91,94,96}};String[] columnKeys = { "测控1班", "测控2班", "信号1班", "信号2班", "信号3班" ,"计通1班","计通2班","城轨1班","城轨2班","计应1班","计应2班"};String[] rowKeys = {"2021级","2021级","2021级","2021级"};new A ttendance(data,rowKeys,columnKeys );ut,;etItemFont(new Font("华文行楷",,20));//设置上下左右显示位置;;//这句代码解决了底部汉字乱码的问题(new Font("华文行楷",,20));//显示每一个柱的数值,并修改该数值的字体属性(new StandardCategoryItemLabelGenerator());//显示每一个柱的数值(true);//注意:此句很关键,若无此句,那数字的显示会被覆盖,给人数字没有显示出来的问题//(new ItemLabelPosition( , );(10D);// 设置柱形图上的文字偏离值//(true);(render);//利用咱们设计的效果//设置纵横坐标的显示位置//学校显示在下端(柱子竖直)或左侧(柱子水平);//人数显示在下端(柱子水平)或左侧(柱子竖直);//设定柱子上面的颜色(0, ; // 给series1 Bar(1, ("#8979FF")); // 给series2 Bar(2, ; // 给series4 Bar(3, new Color(200, 50, 50)); // 给series5 Bar(0,;//边框为黑色(1,;//边框为黑色(2,; //边框为黑色(3,;//边框为黑色FileOutputStream gf = null;try{gf = new F ileOutputStream("E:\\");//将报表保留为JPG文件(gf, //文件保留物理路径包括路径和文件名1f, //图片质量chart, //图表对象1600, //图像宽度668, //图像高度null); //显示信息}finally{try{//关闭输出流();"success");}catch(Exception e){}}}}。
java利用JFreeChart实现各种数据统计图(柱形图,饼图,折线图)最近在做数据挖掘的课程设计,需要将数据分析的结果很直观的展现给用户,这就要用到数据统计图,要实现这个功能就需要几个第三方包了:1. jfreec hart-1.0.13.jar2. jcommo n-1.0.16.jar3. gnujax p.jar先来看一下,最终效果图:主要是jfr eecha rt-1.0.13.jar,但这三个包要齐全,我已经将所有与jfre echar t有关的j ar包与本文实例的工程(代码)一同压缩上传了,有兴趣的同学可以下载,下载地址:http://downlo /detail/pzhtpf/4327700接下来,我们一步步来实现本程序。
一,前期准备工作,也就把这三个第三方包添加进本文工程,添加过程特别简单,前面写过一篇博客,讲的是jav a如何读取Excel表格中的数据(有兴趣的同学可以看一看:/pzhtpf/articl e/detail s/7506135),也要添加第三方包,添加过程一模一样,这里我们在复习一遍:1,建,立java项目,在这个项目在建立一个新的文件夹l i b;2,将上述三个jar包,复制到lib3,然后右键点击这个jav a项目,选择Prop ertie s4,在左侧列表里选中Jav a BuildPath,右侧选中Li brari es5,点击AddJARs6,然后去选择这个项目中lib文件夹中的三个jar,点击确定成功后,项目中会多一个文件夹为:Refere ncedLibrar ies二,实现柱形图的java代码:import java.awt.Font;import org.jfree.chart.ChartF actor y;import org.jfree.chart.ChartP anel;import org.jfree.chart.JFreeC hart;import org.jfree.chart.axis.Catego ryAxi s;import org.jfree.chart.axis.ValueA xis;import org.jfree.chart.plot.Catego ryPlo t;import org.jfree.chart.plot.PlotOr ienta tion;import org.jfree.data.catego ry.Catego ryDat aset;import org.jfree.data.catego ry.Defaul tCate goryD atase t;public classBarCha rt {ChartP anelframe1;public BarCha rt(){Catego ryDat asetdatase t = getDat aSet();JFreeC hartchart= ChartF actor y.create BarCh art3D("水果", // 图表标题"水果种类", // 目录轴的显示标签"数量", // 数值轴的显示标签datase t, // 数据集PlotOr ienta tion.VERTIC AL, // 图表方向:水平、垂直true, // 是否显示图例(对于简单的柱状图必须是false)false, // 是否生成工具false // 是否生成UR L链接);//从这里开始Catego ryPlo t plot=chart.getCat egory Plot();//获取图表区域对象Catego ryAxi s domain Axis=plot.getDom ainAx is(); //水平底部列表domain Axis.setLab elFon t(new Font("黑体",Font.BOLD,14)); //水平底部标题domain Axis.setTic kLabe lFont(new Font("宋体",Font.BOLD,12)); //垂直标题ValueA xis rangeA xis=plot.getRan geAxi s();//获取柱状rangeA xis.setLab elFon t(new Font("黑体",Font.BOLD,15));chart.getLeg end().setIte mFont(new Font("黑体", Font.BOLD, 15));chart.getTit le().setFon t(new Font("宋体",Font.BOLD,20));//设置标题字体//到这里结束,虽然代码有点多,但只为一个目的,解决汉字乱码问题frame1=new ChartP anel(chart,true); //这里也可以用chart Frame,可以直接生成一个独立的Frame}privat e static Catego ryDat asetgetDat aSet() {Defaul tCate goryD atase t datase t = new Defaul tCate goryD atase t();datase t.addVal ue(100, "北京", "苹果");datase t.addVal ue(100, "上海", "苹果");datase t.addVal ue(100, "广州", "苹果");datase t.addVal ue(200, "北京", "梨子");datase t.addVal ue(200, "上海", "梨子");datase t.addVal ue(200, "广州", "梨子"); datase t.addVal ue(300, "北京", "葡萄"); datase t.addVal ue(300, "上海", "葡萄"); datase t.addVal ue(300, "广州", "葡萄"); datase t.addVal ue(400, "北京", "香蕉"); datase t.addVal ue(400, "上海", "香蕉"); datase t.addVal ue(400, "广州", "香蕉"); datase t.addVal ue(500, "北京", "荔枝"); datase t.addVal ue(500, "上海", "荔枝"); datase t.addVal ue(500, "广州", "荔枝"); return datase t;}public ChartP anelgetCha rtPan el(){return frame1;}}效果图如下:但我们把pr ivate static Catego ryDat asetgetDat aSet(){}方法中的数据变化一下后,又会形成另一种效果,比如说我们改成:privat e static Catego ryDat asetgetDat aSet() {Defaul tCate goryD atase t datase t = new Defaul tCate goryD atase t(); datase t.addVal ue(100, "苹果", "苹果");datase t.addVal ue(200, "梨子", "梨子");datase t.addVal ue(300, "葡萄", "葡萄");datase t.addVal ue(400, "香蕉", "香蕉");datase t.addVal ue(500, "荔枝", "荔枝");return datase t;}效果图如下:三,实现饼状图的java代码:packag e com.njue.testJF reeCh art;import java.awt.Font;import java.text.Decima lForm at; import java.text.Number Forma t;import javax.swing.JPanel;import org.jfree.chart.ChartF actor y;import org.jfree.chart.ChartP anel;import org.jfree.chart.JFreeC hart;import org.jfree.chart.labels.Standa rdPie Secti onLab elGen erato r;import org.jfree.chart.plot.PiePlo t;import org.jfree.data.genera l.Defaul tPieD atase t;public classPieCha rt {ChartP anelframe1;public PieCha rt(){Defaul tPieD atase t data = getDat aSet();JFreeC hartchart= ChartF actor y.create PieCh art3D("水果产量",data,true,false,false);//设置百分比PiePlo t pieplo t = (PiePlo t) chart.getPlo t();Decima lForm at df = new Decima lForm at("0.00%");//获得一个De cimal Forma t对象,主要是设置小数问题Number Forma t nf = Number Forma t.getNum berIn stanc e();//获得一个Nu mberF ormat对象Standa rdPie Secti onLab elGen erato r sp1 = newStanda rdPie Secti onLab elGen erato r("{0} {2}", nf, df);//获得Stan dardP ieSec tionL abelG enera tor对象pieplo t.setLab elGen erato r(sp1);//设置饼图显示百分比//没有数据的时候显示的内容pieplo t.setNoD ataMe ssage("无数据显示");pieplo t.setCir cular(false);pieplo t.setLab elGap(0.02D);pieplo t.setIgn oreNu llVal ues(true);//设置不显示空值pieplo t.setIgn oreZe roVal ues(true);//设置不显示负值frame1=new ChartP anel(chart,true);chart.getTit le().setFon t(new Font("宋体",Font.BOLD,20));//设置标题字体PiePlo t piePlo t= (PiePlo t) chart.getPlo t();//获取图表区域对象packag e com.njue.testJF reeCh art;import java.awt.Font;import java.text.Simple DateF ormat;import org.jfree.chart.ChartF actor y; import org.jfree.chart.ChartP anel;import org.jfree.chart.JFreeC hart;import org.jfree.chart.axis.DateAx is; import org.jfree.chart.axis.ValueA xis;import org.jfree.chart.plot.XYPlot;import org.jfree.data.time.Month;import org.jfree.data.time.TimeSe ries;import org.jfree.data.time.TimeSe riesC ollec tion;import org.jfree.data.xy.XYData set;public classTimeSe riesC hart{ChartP anelframe1;public TimeSe riesC hart(){XYData set xydata set = create Datas et();JFreeC hartjfreec hart=ChartF actor y.create TimeS eries Chart("Legal& Genera l单位信托基金价格", "日期", "价格",xydata set, true, true, true);XYPlot xyplot = (XYPlot) jfreec hart.getPlo t();DateAx is dateax is = (DateAx is) xyplot.getDom ainAx is();dateax is.setDat eForm atOve rride(new Simple DateF ormat("MMM-yyyy"));frame1=new ChartP anel(jfreec hart,true);dateax is.setLab elFon t(new Font("黑体",Font.BOLD,14)); //水平底部标题dateax is.setTic kLabe lFont(new Font("宋体",Font.BOLD,12)); //垂直标题 ValueA xis rangeA xis=xyplot.getRan geAxi s();//获取柱状rangeA xis.setLab elFon t(new Font("黑体",Font.BOLD,15));jfreec hart.getLeg end().setIte mFont(new Font("黑体", Font.BOLD, 15)); jfreec hart.getTit le().setFon t(new Font("宋体",Font.BOLD,20));//设置标题字体}privat e static XYData set create Datas et() { //这个数据集有点多,但都不难理解TimeSe riestimese ries= new TimeSe ries("legal& genera l欧洲指数信任",org.jfree.data.time.Month.class);timese ries.add(new Month(2, 2001), 181.80000000000001D);timese ries.add(new Month(3, 2001), 167.30000000000001D);timese ries.add(new Month(4, 2001), 153.80000000000001D);timese ries.add(new Month(5, 2001), 167.59999999999999D);timese ries.add(new Month(6, 2001), 158.80000000000001D);timese ries.add(new Month(7, 2001), 148.30000000000001D);timese ries.add(new Month(8, 2001), 153.90000000000001D);timese ries.add(new Month(9, 2001), 142.69999999999999D);timese ries.add(new Month(10, 2001), 123.2D);timese ries.add(new Month(11, 2001), 131.80000000000001D);timese ries.add(new Month(12, 2001), 139.59999999999999D);timese ries.add(new Month(1, 2002), 142.90000000000001D);timese ries.add(new Month(2, 2002), 138.69999999999999D);timese ries.add(new Month(3, 2002), 137.30000000000001D);timese ries.add(new Month(4, 2002), 143.90000000000001D);timese ries.add(new Month(5, 2002), 139.80000000000001D);timese ries.add(new Month(6, 2002), 137D);timese ries.add(new Month(7, 2002), 132.80000000000001D);TimeSe riestimese ries1 = new TimeSe ries("legal& genera l英国指数信任",org.jfree.data.time.Month.class);timese ries1.add(new Month(2, 2001), 129.59999999999999D);timese ries1.add(new Month(3, 2001), 123.2D);timese ries1.add(new Month(4, 2001), 117.2D);timese ries1.add(new Month(5, 2001), 124.09999999999999D);timese ries1.add(new Month(6, 2001), 122.59999999999999D);timese ries1.add(new Month(7, 2001), 119.2D);timese ries1.add(new Month(8, 2001), 116.5D);timese ries1.add(new Month(9, 2001), 112.7D);timese ries1.add(new Month(10, 2001), 101.5D);timese ries1.add(new Month(11, 2001), 106.09999999999999D);timese ries1.add(new Month(12, 2001), 110.3D);timese ries1.add(new Month(1, 2002), 111.7D);timese ries1.add(new Month(2, 2002), 111D);timese ries1.add(new Month(3, 2002), 109.59999999999999D);timese ries1.add(new Month(4, 2002), 113.2D);timese ries1.add(new Month(5, 2002), 111.59999999999999D);timese ries1.add(new Month(6, 2002), 108.8D);timese ries1.add(new Month(7, 2002), 101.59999999999999D);TimeSe riesC ollec tiontimese riesc ollec tion= newTimeSe riesC ollec tion();timese riesc ollec tion.addSer ies(timese ries);timese riesc ollec tion.addSer ies(timese ries1);return timese riesc ollec tion;}public ChartP anelgetCha rtPan el(){return frame1;}}效果图如下:再来看一下主方法:import java.awt.GridLa yout;import javax.swing.JFrame;public classmainCl ass {public static void main(String args[]){JFrame frame=new JFrame("Java数据统计图");frame.setLay out(new GridLa yout(2,2,10,10));frame.add(new BarCha rt().getCha rtPan el()); //添加柱形图frame.add(new BarCha rt1().getCha rtPan el()); //添加柱形图的另一种效果frame.add(new PieCha rt().getCha rtPan el()); //添加饼状图frame.add(new TimeSe riesC hart().getCha rtPan el()); //添加折线图frame.setBou nds(50, 50, 800, 600);frame.setVis ible(true);}}五,总结以上都是一个简单的例子去实现了,想了解更深的同学可自行查询资料,其实以上代码都通俗易懂,只要结合自己的实际情况,便可开发出属于自己的A pplic ation,大家可以看出我这里是在Appli catio n上实现的,其实更多情况数据统计图在java web上应用更多,大家也可自行了解。
折线图jfreechart:JFreeChart折线图总结疯狂代码 / ĵ:http://Java/Article21473.html 我的编程环境是eclipse3.20+Orcal10g,使用的框架是struts1.2,写log使用的是log4j。
首先,我们必须引入开发所使用的包。
网上的介绍都说大部分需要3个包。
jcommon-1.0.14.jar和jfreechart-1.0.11.jar,还有另外一个包,可是我在操作中发现,引入上述3个包,我的tomcat在启动时总会出错,与现有的程序包有冲突。
后来在同事的帮助下,才发现只要上述前两个包就可以了。
将这两个包放入tomcat的lib中,并增加这两个包的环境变量。
修改web.xml,增加相应的servlet。
<servlet><servlet-name>DisplayChart</servlet-name><servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class></servlet><!-- Action Servlet Mapping --><servlet-mapping><servlet-name>DisplayChart</servlet-name><url-pattern>/servlet/DisplayChart</url-pattern></servlet-mapping> 接下来,我们便可以编写程序了。
我的需求是在后台处理完数据后,生成时间金额的一个统计图,然后在web页中显示图片。
JFreeChart可以产生不同类型的统计图,如饼图,折线图,曲线图,柱状图等。
它很好的使用了工厂模式,所有这些类型的图都需要相应在工厂ChartFactory中生成出相应的chart对象。
最近公司使用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 ={ "失败率", "成功率" };createV alidityComparePimChar(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.setV alue(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轴设置V alueAxis 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_PA TH);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.setV erticalCategoryLabels(false);plot.setDomainAxis(domainAxis);V alueAxis 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_PA TH);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 createV alidityComparePimChar(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("无对应的数据,请重新查询。