1. 程式人生 > >Java實現jFreeChart--折線圖

Java實現jFreeChart--折線圖

  1. public class LineChart2 {
  2. public static String genLineChart(HttpSession session)throws Exception{
  3. // 訪問量統計
  4. TimeSeries timeSeries=new TimeSeries("A網站訪問量統計", Month.class);
  5. // 新增資料
  6. timeSeries.add(new Month(1,2013), 100);
  7. timeSeries.add(new Month(2,2013), 200);
  8. timeSeries.add(new Month(3,2013), 300);
  9. timeSeries.add(new Month(4,2013), 400);
  10. timeSeries.add(new Month(5,2013), 560);
  11. timeSeries.add(new Month(6,2013), 600);
  12. timeSeries.add(new Month(7,2013), 750);
  13. timeSeries.add(new Month(8,2013), 890);
  14. timeSeries.add(new Month(9,2013), 120);
  15. timeSeries.add(new Month(10,2013), 400);
  16. timeSeries.add(new Month(11,2013), 1200);
  17. timeSeries.add(new Month(12,2013), 1600);
  18. // 訪問量統計
  19. TimeSeries timeSeries2=new TimeSeries("B網站訪問量統計", Month.class);
  20. // 新增資料
  21. timeSeries2.add(new Month(1,2013), 50);
  22. timeSeries2.add(new Month(2,2013), 100);
  23. timeSeries2.add(new Month(3,2013), 150);
  24. timeSeries2.add(new Month(4,2013), 200);
  25. timeSeries2.add(new Month(5,2013), 220);
  26. timeSeries2.add(new Month(6,2013), 300);
  27. timeSeries2.add(new Month(7,2013), 340);
  28. timeSeries2.add(new Month(8,2013), 400);
  29. timeSeries2.add(new Month(9,2013), 450);
  30. timeSeries2.add(new Month(10,2013), 500);
  31. timeSeries2.add(new Month(11,2013), 70);
  32. timeSeries2.add(new Month(12,2013), 800);
  33. // 定義時間序列的集合
  34. TimeSeriesCollection lineDataset=new TimeSeriesCollection();
  35. lineDataset.addSeries(timeSeries);
  36. lineDataset.addSeries(timeSeries2);
  37. JFreeChart chart=ChartFactory.createTimeSeriesChart("訪問量統計時間折線圖", "月份", "訪問量", lineDataset, true, true, true);
  38. //設定主標題
  39. chart.setTitle(new TextTitle("A,B網站訪問量統計對比圖", new Font("隸書", Font.ITALIC, 15)));
  40. //設定子標題
  41. TextTitle subtitle = new TextTitle("2013年度", new Font("黑體", Font.BOLD, 12));
  42. chart.addSubtitle(subtitle);
  43. chart.setAntiAlias(true);
  44. //設定時間軸的範圍。
  45. XYPlot plot = (XYPlot) chart.getPlot();
  46. DateAxis dateaxis = (DateAxis)plot.getDomainAxis();
  47. dateaxis.setDateFormatOverride(new java.text.SimpleDateFormat("M月"));
  48. dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH,1));
  49. //設定曲線是否顯示資料點
  50. XYLineAndShapeRenderer xylinerenderer = (XYLineAndShapeRenderer)plot.getRenderer();
  51. xylinerenderer.setBaseShapesVisible(true);
  52. //設定曲線顯示各資料點的值
  53. XYItemRenderer xyitem = plot.getRenderer();
  54. xyitem.setBaseItemLabelsVisible(true);
  55. xyitem.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
  56. xyitem.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
  57. xyitem.setBaseItemLabelFont(new Font("Dialog", 1, 12));
  58. plot.setRenderer(xyitem);
  59. String fileName=ServletUtilities.saveChartAsPNG(chart, 700, 500, session);
  60. return fileName;
  61. }
  62. }