java 饼图

import java.awt.Color;

import java.awt.Font;

import java.io.PrintWriter;

import java.text.DecimalFormat;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.jfree.chart.ChartFactory;

import org.jfree.chart.ChartRenderingInfo;

import org.jfree.chart.ChartUtilities;

import org.jfree.chart.JFreeChart;

import org.jfree.chart.axis.CategoryAxis;

import org.jfree.chart.entity.StandardEntityCollection;

import org.jfree.chart.labels.ItemLabelAnchor;

import org.jfree.chart.labels.ItemLabelPosition;

import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;

import org.jfree.chart.labels.StandardPieSectionLabelGenerator;

import org.jfree.chart.labels.StandardPieToolTipGenerator;

import org.jfree.chart.plot.CategoryPlot;

import org.jfree.chart.plot.PiePlot3D;

import org.jfree.chart.plot.PlotOrientation;

import org.jfree.chart.renderer.category.BarRenderer3D;

import org.jfree.chart.servlet.ServletUtilities;

import org.jfree.data.category.DefaultCategoryDataset;

import org.jfree.data.general.DefaultPieDataset;

import org.jfree.ui.TextAnchor;

 

public class ChartGenerater{ 

    /**

    * @ 利用JFreeChart生成柱形及饼状图

    * @version  JFreeChart 1.08

    * @ List list 生成图形的源数据

    * @ String titles 标题

    * @ String x 图形的水平轴注释

    * @ String y 图形的垂直轴注释

    * @ String charttype 图形类型,piechart为饼图,barchart为柱形图

    */

 

    public static String generateChart(List list, String titles,

           HttpSession session, PrintWriter pw, String x, String y,

           String charttype) {

       String filename = "";

       Font font;

       int len = list.size();

       if ("piechart".equals(charttype.trim())) {

           try {

              // 建立PieDataSet

              DefaultPieDataset dataset = new DefaultPieDataset();

              // 生成一个3D饼图

              for(int i=0;i<len;i++) {

                  String[] rows = (String[]) list.get(i);

                  double count = Double.parseDouble(rows[1]);

                  dataset.setValue(""+(i+1), count);

                 

              }

              PiePlot3D plot = new PiePlot3D(dataset);

              for(int i=0;i<len;i++){

                  plot.setSectionPaint(i, getAwtCol(i));

              }

              plot.setForegroundAlpha(0.6f); // 设置透明度

              plot.setCircular(true, false);

              //plot.setNoDataMessage("There aren't anything!");

              plot.setLabelGenerator(new StandardPieSectionLabelGenerator("({0}):{2}",new DecimalFormat("0"), new DecimalFormat("0.0%")));

              plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{2}",new DecimalFormat("0"), new DecimalFormat("0.0%")));

              plot.setToolTipGenerator(new StandardPieToolTipGenerator());

                //font = new Font("SimSun",Font.BOLD, 15);// 设置统计图标题的字体和大小 Lucida Sans simsun

              JFreeChart chart = new JFreeChart("",JFreeChart.DEFAULT_TITLE_FONT, plot, true);

              /*

                     JFreeChart chart = ChartFactory.createPieChart("招聘网统计图表", // 图表标题

                       data, true, // 是否显示图例

                       false, false); //写图表对象到文件,参照柱状图生成源码

               */

              chart.setTextAntiAlias(true);//设置标题平滑效果

              chart.setBorderVisible(false);//设置图片外边框显示

              //TextTitle tt = new TextTitle(unescape(titles));

              //tt.setFont(font);

              chart.setBackgroundPaint(java.awt.Color.white);// 统计图片的底色

              //chart.setTitle(tt);

              // 把生成的文件写入到临时的目录中

              ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

              filename = ServletUtilities.saveChartAsPNG(chart, 500, 350,info, session);

              // 选择存储成png格式的文件,当然你也可以使用saveChartAsJPEG的方法生成jpg图片

              // 把image map 写入到 PrintWriter

              ChartUtilities.writeImageMap(pw, filename, info, false);

              pw.flush();

           } catch (Exception ex) {

              System.err.println("error:" + ex.getMessage());

           }

       }

 

       // 生成柱形图

       if ("barchart".equals(charttype.trim())) {

           try {

              BarRenderer3D renderer = new BarRenderer3D();

              DefaultCategoryDataset dataset = new DefaultCategoryDataset();

              for (int i = 0; i < len; i++) {

                  String[] rows = (String[]) list.get(i);

                  int count = Integer.parseInt(rows[1]);

                  dataset.setValue(count, ""+(i+1), ""+(i+1));

                  renderer.setSeriesPaint(i, getAwtCol(i));

              }

              JFreeChart chart = ChartFactory.createBarChart3D(" ", x, y, dataset,PlotOrientation.VERTICAL, false, false, false);

              chart.setBackgroundPaint(Color.WHITE);

              CategoryPlot plot = chart.getCategoryPlot();

              CategoryAxis domainAxis = plot.getDomainAxis();

              domainAxis.setAxisLineVisible(true);

              plot.setDomainAxis(domainAxis);

             

              renderer.setBaseOutlinePaint(Color.BLACK);

              // 设置每个地区所包含的平行柱的之间距离

              renderer.setItemMargin(0.06);

             

              // 显示每个柱的数值,并修改该数值的字体属性

              renderer.setBaseItemLabelsVisible(true);

              renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());

                font = new Font("SimSun",Font.BOLD,12); //Lucida Sans

              renderer.setBaseItemLabelFont(font);

              renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(

                     ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));

              //ValueAxis rangeAxis = plot.getRangeAxis();

//             设置最高的一个柱与图片顶端的距离

              //rangeAxis.setUpperMargin(0.15);

//            设置最低的一个柱与图片底端的距离

//            rangeAxis.setLowerMargin(0.15);

              //plot.setRangeAxis(rangeAxis);

              //plot.setNoDataMessage("There aren't anything!");

              plot.setRenderer(renderer);

              plot.setRangeGridlinesVisible(true);

              // 设置柱的透明度

              plot.setForegroundAlpha(0.8f);

              StandardEntityCollection sec = new StandardEntityCollection();

              ChartRenderingInfo info = new ChartRenderingInfo(sec);

              // 500是图片长度,300是图片高度

              filename = ServletUtilities.saveChartAsPNG(chart, 500, 280,

                     info, session);

              ChartUtilities.writeImageMap(pw, filename, info, false);

              pw.flush();

           } catch (Exception ex) {

              System.err.println("error:" + ex.getMessage());

           }

       }

       return filename;

    }

 

    public static String unescape(Object obj) {

       if (obj == null)

           return "";

       String str = obj.toString().trim();

       StringBuffer sb = new StringBuffer(str.length());

       int len = 0;

       int pos = 0;

       char ch;

       while (len < str.length()) {

           pos = str.indexOf("%", len);

           if (pos == len) {

              if (str.charAt(pos + 1) == 'u') {

                  ch = (char) Integer.parseInt(str

                         .substring(pos + 2, pos + 6), 16);

                  sb.append(ch);

                  len = pos + 6;

              } else {

                  ch = (char) Integer.parseInt(str

                         .substring(pos + 1, pos + 3), 16);

                  sb.append(ch);

                  len = pos + 3;

              }

           } else {

              if (pos == -1) {

                  sb.append(str.substring(len));

                  len = str.length();

              } else {

                  sb.append(str.substring(len, pos));

                  len = pos;

              }

           }

       }

       return sb.toString();

    }

   

   

    public static Color getAwtCol(int i){

       if(i > 9) return Color.BLUE;

       Color[] cols = new Color[]{

              Color.RED,

              Color.BLUE,

              Color.BLACK,

              Color.YELLOW,

              Color.GREEN,

              Color.MAGENTA,

              Color.ORANGE,

              Color.PINK,

              Color.DARK_GRAY,

              Color.CYAN

       };

       return cols[i];

    }

}

 

页面调用

           filename = CRMChartGenerater.generateChart(list,escape(title),session, new java.io.PrintWriter(out),"","",charttype);      

           graphURL = request.getContextPath() + "/chart?filename=" + filename;

 

<img src="<%=graphURL %>"  border=0 usemap="#<%= filename %>"/> 

你可能感兴趣的:(java,UI,servlet,jfreechart,招聘)