这两天客户要求做个正态分布图,发现我们用的报表工具都不能直接生成正态分布图,如报表工具ireport和BI工具cognos,一般只支持折线图。在网上搜了下,找到jfreechart可以实现。

         以下是jsp页面代码:

<%@ page import="org.jfree.chart.plot.PlotOrientation" %>
<%@ page import="java.io.PrintWriter" %>
<%@ page import="org.jfree.chart.servlet.ServletUtilities" %>
<%@ page import="org.jfree.chart.entity.StandardEntityCollection" %>
<%@ page import="org.jfree.data.function.Function2D" %>
<%@ page import="org.jfree.data.function.NormalDistributionFunction2D" %>
<%@ page import="org.jfree.data.xy.XYDataset" %>
<%@ page import="org.jfree.data.general.DatasetUtilities" %>
<%@ page import="com.apex.util.ApexRowSet" %>
<%@ page import="com.apex.util.Util" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="org.jfree.chart.*" %>

<%@ page contentType="text/html; charset=GBK" %>

<%

   float score = 0.0f;

   // score 是通过sql查询出的均分


    Function2D normal = new NormalDistributionFunction2D(score, 10);
    XYDataset dataset = DatasetUtilities.sampleFunction2D(normal, 0, 100, 100, "Normal");
    final JFreeChart chart = ChartFactory.createXYLineChart(
            "成绩正态分布图",
            "X",
            "Y",
            dataset,
            PlotOrientation.VERTICAL,
            true,
            true,
            false
    );

    String chartName = generateChart(chart, session, new PrintWriter(out), 760, 410);
%>

<%!
    public static String generateChart(JFreeChart chart, HttpSession session,
                                       PrintWriter pw, int width, int height) {
        String chartName = "";
        String path = System.getProperty("java.io.tmpdir");
        path = path.replace("temp", "");
        System.setProperty("java.io.tmpdir",path+"LiveBos\\FormBuilder\\tmp");
        try {
            ChartRenderingInfo info = new ChartRenderingInfo(
                    new StandardEntityCollection());
            chartName = ServletUtilities.saveChartAsPNG(chart, width, height,
                    session);
            /** 将图片地图写入PW中 */
            ChartUtilities.writeImageMap(pw, chartName, info, false);
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.setProperty("java.io.tmpdir",path+"temp");
        }
        return chartName;
    }
%>


       
   

 说明:

1.生成临时图片文件,默认目录在tomcat的temp目录,可以通过启动文件中修改该路径。上面程序是修改了动态修改了路径,又设置回去了。