需要导入的包:
1 import org.jfree.chart.*;
2 import org.jfree.chart.plot.PlotOrientation;
3 import org.jfree.data.category.DefaultCategoryDataset;
4 import org.jfree.data.general.SeriesException;
5 import org.jfree.data.time.Second;
6 import org.jfree.data.time.TimeSeries;
7 import org.jfree.data.time.TimeSeriesCollection;
8 import org.jfree.data.xy.XYDataset;
若是maven工程,需要引入依赖如下:
1 <dependency>
2 <groupId>jfree</groupId>
3 <artifactId>jfreechart</artifactId>
4 <version>1.0.13</version>
5 </dependency>
1 /**
2 * 生成xy图
3 */
4 public static void drawXYChart(String imgTitle,String xLable,String yLabel,XYDataset dataset,String imgPath) {
5 try {
6 JFreeChart timechart = ChartFactory.createTimeSeriesChart(imgTitle, xLable, yLabel,
7 dataset, false, false, false);
8 //定义图片宽度和高度
9 int width = 560;
10 int height = 370;
11 File timeChart = new File(imgPath);
12 //图片以JPEG格式保存
13 ChartUtilities.saveChartAsJPEG(timeChart, timechart, width, height);
14 }catch (Exception e){
15 e.printStackTrace();
16 }
17
18 }
1 public static void main(final String[] args) throws Exception {
2 final TimeSeries series = new TimeSeries("Random Data");
3 XYDataset dataset = (XYDataset) new TimeSeriesCollection(series);
4 List<Long[]> list = new ArrayList<>();
5 list.add(...) //添加一些测试数据来填充list对象
6 for(Long[] item : list){
7 Second current = new Second(new Date(item[0]));
8 series.add(current,item[1]);
9 }
10 DrawImgUtil.drawXYChart("computing Test","Seconds","Value",dataset, "/Users/test/per/" + imgName );
11
12 }
生成图片如下: