通過JFreeChart插件還可以生成擁有多個繪圖區的圖表,簡稱組合圖表,在生成組合圖表時,必須通過繪圖區對象,因爲JFreeChart允許向繪圖區對象中添加子繪圖區對象。
下面是一個組合圖表的典型應用,下面將以此講解組合圖表的具體生成方法。
分析一下圖14.11中的兩個繪圖區,每個繪圖區擁有各自的X軸,該圖左側的Y軸爲兩個繪圖區共用的Y軸,使用該Y軸的圖例有“漲幅百分比”和“今日漲幅之最”,圖例“今日股價之最”使用右側的Y軸,右側的Y軸爲右側繪圖區的附加軸,生成原理同14.7節,然後看一下圖14.11的具體生成方法。
該典型應用生成的組合圖表的效果如圖14.11所示。
圖14.11 利用JFreeChart生成組合圖表
程序實現過程如下。
(1)首先定義右側子繪圖區,代碼如下:
// 創建一個繪圖區對象
XYPlot plot1 = new XYPlot();
// 定義獨立的X軸
DateAxis axis1 = new DateAxis("今日之最");
DateTickUnit unit1 = new DateTickUnit(DateTickUnit.HOUR, 1, new SimpleDateFormat("HH"));
axis1.setTickUnit(unit1);
plot1.setDomainAxis(axis1);
// 因爲共用Y軸,所以將其設爲空
plot1.setRangeAxis(null);
// 設定繪圖數據集,數據集在前面已經封裝完畢,這裏不再詳細介紹
plot1.setDataset(dataset1);
// 定義繪圖風格
XYLineAndShapeRenderer xyArea1 = new XYLineAndShapeRenderer();
plot1.setRenderer(xyArea1);
(2)在右側的繪圖區中添加一個附加軸,用來統計股票的具體價格,代碼如下:
// 創建附加軸對象,並添加到繪圖區
ValueAxis axis11 = new NumberAxis("股票價格(單位:元 / 股)");
axis11.setUpperBound(30.0); // 設置Y軸最大值
axis11.setLowerBound(10.0); // 設置Y軸最小值
plot1.setRangeAxis(1, axis11);
// 創建與附加軸對應的數據集,並添加到繪圖區
TimeSeries timeSeries11 = new TimeSeries("今日股價之最", Minute.class);
timeSeries11.add(startMinute, yesterdayValue);
timeSeries11.add(minMinute, yesterdayValue + yesterdayValue * minPercent);
timeSeries11.add(maxMinute, yesterdayValue + yesterdayValue * maxPercent);
timeSeries11.addOrUpdate(endMinute, yesterdayValue + yesterdayValue * endPercent);
IntervalXYDataset dataset11 = new TimeSeriesCollection(timeSeries11);
plot1.setDataset(1, dataset11);
// 將繪圖數據集映射到附加軸上
plot1.mapDatasetToRangeAxis(1, 1);
// 定義附加軸的繪圖風格,這裏爲折線
XYLineAndShapeRenderer xyArea11 = new XYLineAndShapeRenderer();
plot1.setRenderer(1, xyArea11);
(3)定義左側子繪圖區,代碼如下:
// 創建一個繪圖區對象
XYPlot plot2 = new XYPlot();
// 定義獨立的X軸
DateAxis axis2 = new DateAxis("統計時間");
DateTickUnit unit2 = new DateTickUnit(DateTickUnit.MINUTE, 30,
new SimpleDateFormat("HH:mm"));
axis2.setTickUnit(unit2);
plot2.setDomainAxis(axis2);
// 因爲共用Y軸,所以將其設爲空
plot2.setRangeAxis(null);
// 設定繪圖數據集,數據集在前面已經封裝完畢,這裏不再詳細介紹
plot2.setDataset(dataset2);
// 定義繪圖風格
XYAreaRenderer xyArea2 = new XYAreaRenderer();
plot2.setRenderer(xyArea2);
(4)定義父繪圖區,代碼如下:
// 創建一個繪圖區對象
CombinedRangeXYPlot plot = new CombinedRangeXYPlot();
// 定義共用座標軸
NumberAxis axis = new NumberAxis("股票漲幅百分比");
axis.setTickUnit(new NumberTickUnit(0.025,new DecimalFormat("0.0%")));//定義度量值風格
plot.setRangeAxis(axis);
// 添加子繪圖區
plot.add(plot2, 5);
plot.add(plot1, 2);
說明:在通過繪圖區對象的add()方法添加子繪圖區對象時,第一個入口參數爲欲添加的子繪圖區對象,第二個入口參數爲該繪圖區所佔的比例,上面代碼的意思是plot2佔5/7,plot1佔2/7,還需要注意的是,繪圖區從左到右的排列順序是由添加子繪圖區的先後順序決定的。
下面的代碼是通過上面的父繪圖區對象生成圖表,並獲得瀏覽路徑:
// 創建圖表
JFreeChart chart = new JFreeChart(chartTitle, plot);
// 添加圖表副標題
chart.addSubtitle(new TextTitle(subtitle));
// 固定用法
ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
// 生成指定格式的圖片,並返回圖片名稱
String fileName = ServletUtilities.saveChartAsPNG(chart, width, height, info, session);
// 返回圖片瀏覽路徑
return servletURI + "?filename=" + fileName;
至此,一個組合圖表就繪製完成了,這裏繪製的是共用Y軸的組合圖表,同樣也可以繪製出共用X軸的組合圖表。