Java實現jFreeChart--折線圖
阿新 • • 發佈:2018-12-11
- public class LineChart2 {
- public static String genLineChart(HttpSession session)throws Exception{
- // 訪問量統計
- TimeSeries timeSeries=new TimeSeries("A網站訪問量統計", Month.class);
- // 新增資料
- timeSeries.add(new Month(1,2013), 100);
- timeSeries.add(new Month(2,2013), 200);
- timeSeries.add(new Month(3,2013), 300);
- timeSeries.add(new Month(4,2013), 400);
- timeSeries.add(new Month(5,2013), 560);
- timeSeries.add(new Month(6,2013), 600);
- timeSeries.add(new Month(7,2013), 750);
- timeSeries.add(new Month(8,2013), 890);
- timeSeries.add(new Month(9,2013), 120);
- timeSeries.add(new Month(10,2013), 400);
- timeSeries.add(new Month(11,2013), 1200);
- timeSeries.add(new Month(12,2013), 1600);
- // 訪問量統計
- TimeSeries timeSeries2=new TimeSeries("B網站訪問量統計", Month.class);
- // 新增資料
- timeSeries2.add(new Month(1,2013), 50);
- timeSeries2.add(new Month(2,2013), 100);
- timeSeries2.add(new Month(3,2013), 150);
- timeSeries2.add(new Month(4,2013), 200);
- timeSeries2.add(new Month(5,2013), 220);
- timeSeries2.add(new Month(6,2013), 300);
- timeSeries2.add(new Month(7,2013), 340);
- timeSeries2.add(new Month(8,2013), 400);
- timeSeries2.add(new Month(9,2013), 450);
- timeSeries2.add(new Month(10,2013), 500);
- timeSeries2.add(new Month(11,2013), 70);
- timeSeries2.add(new Month(12,2013), 800);
- // 定義時間序列的集合
- TimeSeriesCollection lineDataset=new TimeSeriesCollection();
- lineDataset.addSeries(timeSeries);
- lineDataset.addSeries(timeSeries2);
- JFreeChart chart=ChartFactory.createTimeSeriesChart("訪問量統計時間折線圖", "月份", "訪問量", lineDataset, true, true, true);
- //設定主標題
- chart.setTitle(new TextTitle("A,B網站訪問量統計對比圖", new Font("隸書", Font.ITALIC, 15)));
- //設定子標題
- TextTitle subtitle = new TextTitle("2013年度", new Font("黑體", Font.BOLD, 12));
- chart.addSubtitle(subtitle);
- chart.setAntiAlias(true);
- //設定時間軸的範圍。
- XYPlot plot = (XYPlot) chart.getPlot();
- DateAxis dateaxis = (DateAxis)plot.getDomainAxis();
- dateaxis.setDateFormatOverride(new java.text.SimpleDateFormat("M月"));
- dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH,1));
- //設定曲線是否顯示資料點
- XYLineAndShapeRenderer xylinerenderer = (XYLineAndShapeRenderer)plot.getRenderer();
- xylinerenderer.setBaseShapesVisible(true);
- //設定曲線顯示各資料點的值
- XYItemRenderer xyitem = plot.getRenderer();
- xyitem.setBaseItemLabelsVisible(true);
- xyitem.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
- xyitem.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
- xyitem.setBaseItemLabelFont(new Font("Dialog", 1, 12));
- plot.setRenderer(xyitem);
- String fileName=ServletUtilities.saveChartAsPNG(chart, 700, 500, session);
- return fileName;
- }
- }