JFreeChart柱圖代碼

       

直方條形圖常常被用來顯示錶列數據。如下表,爲一個簡單的兩行、三列數據。

 

Colnums1

Colnums2

Colnums3

Row1

1.0

5.0

3.0

Row2

2.0

3.0

2.0


在這個圖表的實例中,我們可以看到JFreeChart將每列數據(即一個種類)組合在一起。而且對每行數據(即每個系列)使用各種顏色高亮顯示。

       

// 柱狀圖數據集
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        dataset.addValue(300, "Row1", "Column1");
        dataset.addValue(300, "Row1", "Column2");
        dataset.addValue(200, "Row2", "Column1");
        dataset.addValue(300, "Row2", "Column2");
        dataset.addValue(100, "Row3", "Column1");
        dataset.addValue(100, "Row3", "Column2");
        
        JFreeChart chart = ChartFactory.createBarChart(
            "水果產量圖", // 圖表標題
            "水果", // 目錄軸的顯示標籤
            "產量", // 數值軸的顯示標籤
            dataset, // 數據集
            PlotOrientation.VERTICAL, // 圖表方向:水平、垂直
            true,     // 是否顯示圖例(對於簡單的柱狀圖必須是false)
            false,     // 是否生成工具
            false     // 是否生成URL鏈接
        );
        
        CategoryPlot plot = chart.getCategoryPlot();
        // 改變顏色
        BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setSeriesPaint(0, Color.gray);
        renderer.setSeriesPaint(1, Color.orange);
        renderer.setDrawBarOutline(false);
        // 去掉柱條之間的間距
        renderer.setItemMargin(0.0);

        CategoryAxis axis = plot.getDomainAxis();//獲取x軸
        ValueAxis numberAxis = plot.getRangeAxis();//獲取y軸
        //axis.setLowerMargin(0.1);//設置距離圖片左端距離此時爲10%
        //axis.setUpperMargin(0.1);//設置距離圖片右端距離此時爲百分之10
        //axis.setCategoryLabelPositionOffset(10);//圖表橫軸與標籤的距離(10像素)
        //axis.setCategoryMargin(0.2);//橫軸標籤之間的距離20%
        chart.getLegend().setItemFont(new Font("黑體",Font.BOLD,12));//設置底部中文亂碼
        axis.setTickLabelFont(new Font("黑體",Font.BOLD,12));//設置X軸座標上的文字
        axis.setLabelFont(new Font("黑體",Font.BOLD,12));//設置X軸的標題文字
        numberAxis.setTickLabelFont(new Font("黑體",Font.BOLD,12));//設置X軸座標上的文字
        numberAxis.setLabelFont(new Font("黑體",Font.BOLD,12));//設置X軸的標題文字
        chart.getTitle().setFont(new Font("黑體",Font.BOLD,18));//設置標題文字
        
        String filename = ServletUtilities.saveChartAsPNG(chart, 600, 400, null,request.getSession());
        String graphURL = request.getContextPath()+"/displaychart?filename="+filename;
        request.setAttribute("graphURL", graphURL);
        request.getRequestDispatcher("/bar/index.jsp").forward(request, response);   

發佈了35 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章