通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
## 7.3 使用XYDataset数据集创建折线图 ### 7.3.1 概述 折线图也可以使用XYDataset数据集,使用一条直线将相邻的点(x,y)点连接起来。本章介绍的一个使用XYDataset数据集创建折线图的简单实例,如下图7.2所示。 ![](img/jfc45412.png) 图7.2 一个简单的基于XYDataset数据集的折线图(参考:LineChartDemo2.java) ### 7.3.2 XYDataset 对于该图表来说,使用的数据集是XYSeriesCollection(当然我们可以使用实现XYDataset接口的其他数据集)。出于独立演示的目点,我们创建的dataset代码如下: ``` private static XYDataset createDataset() { XYSeries xyseries = new XYSeries("First"); xyseries.add(1.0, 1.0); xyseries.add(2.0, 4.0); xyseries.add(3.0, 3.0); xyseries.add(4.0, 5.0); xyseries.add(5.0, 5.0); xyseries.add(6.0, 7.0); xyseries.add(7.0, 7.0); xyseries.add(8.0, 8.0); XYSeries xyseries_0_ = new XYSeries("Second"); xyseries_0_.add(1.0, 5.0); xyseries_0_.add(2.0, 7.0); xyseries_0_.add(3.0, 6.0); xyseries_0_.add(4.0, 8.0); xyseries_0_.add(5.0, 4.0); xyseries_0_.add(6.0, 4.0); xyseries_0_.add(7.0, 2.0); xyseries_0_.add(8.0, 1.0); XYSeries xyseries_1_ = new XYSeries("Third"); xyseries_1_.add(3.0, 4.0); xyseries_1_.add(4.0, 3.0); xyseries_1_.add(5.0, 2.0); xyseries_1_.add(6.0, 3.0); xyseries_1_.add(7.0, 6.0); xyseries_1_.add(8.0, 3.0); xyseries_1_.add(9.0, 4.0); xyseries_1_.add(10.0, 3.0); XYSeriesCollection xyseriescollection = new XYSeriesCollection(); xyseriescollection.addSeries(xyseries); xyseriescollection.addSeries(xyseries_0_); xyseriescollection.addSeries(xyseries_1_); return xyseriescollection; } ``` 注意:每个系列必须有x值(不是必须有y值),并且该系列独立于其他系列。数据集可以接受一个y值为null的值。当图表遇到null值时,连接线不被画出,该系列的连线不会连续。出现下图7.3类型。 ![](img/jfc46755.png) 图7.3有一个 y值为null时,图表显示断续。 ### 7.3.3 创建图表 ChartFactory类提供了一个便利的方法createXYLineChart()创图表: ``` JFreeChart jfreechart = ChartFactory.createXYLineChart( "Line Chart Demo 2", // chart title "X", // x axis label "Y", // y axis label xydataset, // data PlotOrientation.VERTICAL, true, // include legend true, // tooltips false // urls ); ``` 上面方法构建了一个JFreeChart对象,该对象具有一个标题、图例和相关轴的图区及renderer。数据集使用上节我们创建的数据集。 ### 7.3.4 定制图表 图表将使用大部分缺省的属性进行初始化设置。当然了,我们也可以随意修改这些属性,来改变我们图表的外观。在本实例中,设置的几个属性如下: + 设置图表的背景颜色 + 设置图区的背景颜色 + 设置轴的平移值 + 设置主轴和范围轴网格线颜色 + 修改renderer改变连线点的形状 + 范围轴刻度的设置,以便显示整数值。 改变图表背景颜色非常简单。代码如下: ``` //改变图表的背景颜色 jfreechart.setBackgroundPaint(Color.white); ``` 改变图区背景颜色、轴平移、网格线颜色,需要使用plot图区对象的一个引用来修改。图片对象需要转化成XYPlot对象,主要是因为我们可以访问更多更具体的图区方法。代码如下: ``` XYPlot xyplot = (XYPlot) jfreechart.getPlot(); xyplot.setBackgroundPaint(Color.lightGray); xyplot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); xyplot.setDomainGridlinePaint(Color.white); xyplot.setRangeGridlinePaint(Color.white); ``` 修改renderer来显示连线之间的形状。代码如下: ``` XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyplot.getRenderer(); xylineandshaperenderer.setShapesVisible(true); xylineandshaperenderer.setShapesFilled(true); ``` 最后就是修改范围轴。我们将默认刻度值(允许显示小数)改成只显示整数的刻度值。代码如下: ``` NumberAxis numberaxis = (NumberAxis) xyplot.getRangeAxis(); numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); ``` 参考源代码、Javadoc的API文档以及其他相关XYPlot的定制内容,来学习更多的细节。