예제 #1
0
 private static JFreeChart createChart(PieDataset dataset, String title) {
   JFreeChart chart = ChartFactory.createPieChart3D(title, dataset, true, true, false);
   PiePlot3D plot = (PiePlot3D) chart.getPlot();
   plot.setStartAngle(290.0d);
   plot.setDirection(Rotation.CLOCKWISE);
   plot.setForegroundAlpha(JFreeChart.DEFAULT_BACKGROUND_IMAGE_ALPHA);
   return chart;
 }
예제 #2
0
  /**
   * Cria um grafico de pizza com os dados fornecidos
   *
   * @param titulo <code>String</code> com o titulo do grafico
   * @param listaNomesValores {@code List<NomeValor>} lista com os nomes e valores para o grafico
   * @param legendasAdicionais <code>String...</code> com as legendas adicionais
   * @param graficoEm3D <code>boolean</code> com <code>true</code> se o grafico é em 3D ou não.
   */
  public GraficoPizza(
      String titulo,
      List<NomeValor> listaNomesValores,
      boolean graficoEm3D,
      final String... legendasAdicionais) {
    // Cria um dataSet para inserir os dados que serão passados para a criação do grafico tipo Pie
    DefaultPieDataset pieDataset = new DefaultPieDataset();
    this.graficoEm3D = graficoEm3D;

    // Adiciona os dados ao dataSet deve somar um total de 100%
    double valorUmPorCentoVotos = this.valorUmVotoEmPorCento(listaNomesValores);
    String valor;
    for (NomeValor nomesValores : listaNomesValores) {
      valor = String.format("%.2f%%", nomesValores.getValor() * valorUmPorCentoVotos);
      pieDataset.setValue(nomesValores.getNome() + "(" + valor + ")", nomesValores.getValor());
    }

    // Cria um objeto JFreeChart passando os seguintes parametros
    if (!this.graficoEm3D) {
      this.grafico =
          ChartFactory.createPieChart(
              titulo, // Titulo do grafico
              pieDataset, // DataSet
              true, // Para mostrar ou não a legenda
              true, // Para mostrar ou não os tooltips
              false);
    } else { // em 3D
      this.grafico =
          ChartFactory.createPieChart3D(
              titulo, // Titulo do grafico
              pieDataset, // DataSet
              true, // Para mostrar ou não a legenda
              true, // Para mostrar ou não os tooltips
              false);
    }

    if (this.grafico != null) {
      LegendTitle legenda =
          new LegendTitle(
              new LegendItemSource() {

                @Override
                public LegendItemCollection getLegendItems() {
                  LegendItemCollection legenda = new LegendItemCollection();
                  for (String texto : legendasAdicionais) {
                    legenda.add(new LegendItem(texto));
                  }
                  return legenda;
                }
              });
      float larguraBordaLegenda = 0.6F;
      legenda.setBorder(
          larguraBordaLegenda, larguraBordaLegenda, larguraBordaLegenda, larguraBordaLegenda);
      legenda.setPosition(RectangleEdge.BOTTOM);
      legenda.setHorizontalAlignment(HorizontalAlignment.LEFT);
      this.grafico.addLegend(legenda);
    }
  }
예제 #3
0
 private static JFreeChart createChart(PieDataset piedataset) {
   JFreeChart jfreechart =
       ChartFactory.createPieChart3D("Statitic", piedataset, true, false, false);
   PiePlot3D pieplot3d = (PiePlot3D) jfreechart.getPlot();
   pieplot3d.setStartAngle(270D);
   pieplot3d.setDirection(Rotation.ANTICLOCKWISE);
   pieplot3d.setForegroundAlpha(0.6F);
   return jfreechart;
 }
  // creates JFreeChart pie chart with data set
  private JFreeChart createPieChart(PieDataset dataSet, String title) {
    JFreeChart chart =
        ChartFactory.createPieChart3D(
            title, // chart title
            dataSet, // data
            true, // include legend
            true, false);

    PiePlot3D plot = (PiePlot3D) chart.getPlot();
    plot.setStartAngle(290);
    plot.setDirection(Rotation.CLOCKWISE);
    plot.setForegroundAlpha(0.5f);
    return chart;
  }
예제 #5
0
  @Override
  public JFreeChart createChart(PieDataset pieDataSet, boolean createLegend) {
    JFreeChart chart =
        ChartFactory.createPieChart3D(
            null,
            pieDataSet,
            createLegend, // legend
            true,
            false);

    PiePlot3D plot = (PiePlot3D) chart.getPlot();
    plot.setForegroundAlpha(0.5f);

    return chart;
  }
 private JFreeChart createChart(final PieDataset dataset) {
   final JFreeChart chart =
       ChartFactory.createPieChart3D(
           "Pie Chart 3D Demo 1 ", // chart title
           dataset, // data
           true, // include legend
           true,
           false);
   final PiePlot3D plot = (PiePlot3D) chart.getPlot();
   plot.setStartAngle(290);
   plot.setDirection(Rotation.CLOCKWISE);
   plot.setForegroundAlpha(0.5f);
   plot.setNoDataMessage("No data to display");
   return chart;
 }
예제 #7
0
 public InputStream create3DPieChart(String title, PieDataset data, int pngwidth, int pngheight)
     throws IOException {
   JFreeChart localJFreeChart = ChartFactory.createPieChart3D(title, data, true, true, false);
   PiePlot3D localPiePlot3D = (PiePlot3D) localJFreeChart.getPlot();
   localPiePlot3D.setStartAngle(290.0D);
   localPiePlot3D.setDirection(Rotation.CLOCKWISE);
   localPiePlot3D.setForegroundAlpha(0.5F);
   localPiePlot3D.setNoDataMessage("No data to display");
   localPiePlot3D.setSectionPaint(0, new Color(152, 251, 152));
   localPiePlot3D.setSectionPaint(1, new Color(238, 221, 130));
   localPiePlot3D.setSectionPaint(2, new Color(255, 62, 150));
   localPiePlot3D.setSectionPaint(3, new Color(139, 0, 0));
   localPiePlot3D.setSectionPaint(4, new Color(181, 181, 181));
   ChartRenderingInfo info = new ChartRenderingInfo();
   BufferedImage bi =
       localJFreeChart.createBufferedImage(pngwidth, pngheight, BufferedImage.SCALE_FAST, info);
   ByteArrayOutputStream bs = new ByteArrayOutputStream();
   ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
   ImageIO.write(bi, "GIF", imOut);
   // scaledImage1ΪBufferedImage£¬jpgΪͼÏñµÄÀàÐÍ
   InputStream istream = new ByteArrayInputStream(bs.toByteArray());
   return istream;
 }
  public JFreeChart getChart() {
    JFreeChart chart = null;
    try {
      Font font = new Font("宋体", 0, 20); // 字体
      QuestionStatisticsModel qsm = ss.statistics(qid);
      DefaultPieDataset pieds = null; // 饼图的数据集
      DefaultCategoryDataset cateds = null; // 种类数据集

      if (chartType < 2) {
        pieds = new DefaultPieDataset();
        for (OptionStatisticsModel os : qsm.getOsms()) {
          pieds.setValue(os.getOptionLabel(), os.getCount());
        }
      } else {
        cateds = new DefaultCategoryDataset();
        for (OptionStatisticsModel os : qsm.getOsms()) {
          cateds.setValue(os.getCount(), os.getOptionLabel(), "");
        }
      }

      switch (chartType) {
        case CHARTTYPE_PIE_2D:
          chart =
              ChartFactory.createPieChart(qsm.getQuestion().getTitle(), pieds, true, false, false);
          break;
        case CHARTTYPE_PIE_3D:
          chart =
              ChartFactory.createPieChart3D(qsm.getQuestion().getTitle(), pieds, true, true, true);
          // 设置前景色透明度
          chart.getPlot().setForegroundAlpha(0.6f);
          break;
        case CHARTTYPE_BAR_2D_H: // 平面条形图
          chart =
              ChartFactory.createBarChart(
                  qsm.getQuestion().getTitle(),
                  "",
                  "",
                  cateds,
                  PlotOrientation.HORIZONTAL,
                  true,
                  true,
                  true);
          break;
        case CHARTTYPE_BAR_2D_V: // 平面条形图
          chart =
              ChartFactory.createBarChart(
                  qsm.getQuestion().getTitle(),
                  "",
                  "",
                  cateds,
                  PlotOrientation.VERTICAL,
                  true,
                  true,
                  true);
        case CHARTTYPE_BAR_3D_H: // 平面条形图
          chart =
              ChartFactory.createBarChart3D(
                  qsm.getQuestion().getTitle(),
                  "",
                  "",
                  cateds,
                  PlotOrientation.HORIZONTAL,
                  true,
                  true,
                  true);
        case CHARTTYPE_BAR_3D_V: // 平面条形图
          chart =
              ChartFactory.createBarChart3D(
                  qsm.getQuestion().getTitle(),
                  "",
                  "",
                  cateds,
                  PlotOrientation.VERTICAL,
                  true,
                  true,
                  true);
          break;
          //
        case CHARTTYPE_LINE_2D: // 平面条形图
          chart =
              ChartFactory.createLineChart(
                  qsm.getQuestion().getTitle(),
                  "",
                  "",
                  cateds,
                  PlotOrientation.VERTICAL,
                  true,
                  true,
                  true);
          break;
        case CHARTTYPE_LINE_3D: // 平面条形图
          chart =
              ChartFactory.createLineChart3D(
                  qsm.getQuestion().getTitle(),
                  "",
                  "",
                  cateds,
                  PlotOrientation.HORIZONTAL,
                  true,
                  true,
                  true);
          break;
      }

      chart.getTitle().setFont(font);
      chart.getLegend().setItemFont(font);

      // 设置饼图特效
      if (chart.getPlot() instanceof PiePlot) {
        PiePlot pieplot = (PiePlot) chart.getPlot();
        pieplot.setLabelFont(font);
        pieplot.setExplodePercent(0, 0.1);
        pieplot.setStartAngle(-15);
        pieplot.setDirection(Rotation.CLOCKWISE);
        pieplot.setNoDataMessage("No data to display");
        // pieplot.setForegroundAlpha(0.5f);
        // pieplot.setBackgroundImageAlpha(0.3f);
      }
      // 设置非饼图效果
      else {
        chart.getCategoryPlot().getRangeAxis().setLabelFont(font);
        chart.getCategoryPlot().getRangeAxis().setTickLabelFont(font);
        chart.getCategoryPlot().getDomainAxis().setLabelFont(font);
        chart.getCategoryPlot().getDomainAxis().setTickLabelFont(font);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return chart;
  }
  /* (non-Javadoc)
   * @see com.lily.dap.service.report2.impl.chart.ChartStrategy#outputChart(java.lang.String, int, int, java.util.Map, java.util.List, java.io.OutputStream)
   */
  public void outputChart(
      String type,
      int height,
      int width,
      Map<String, String> paramMap,
      Map<String, Object> variableMap,
      List<Map<String, Object>> dataList,
      OutputStream os)
      throws IOException {
    String nameField = ChartUtils.evaluateParam(paramMap.get("namefield"), variableMap);
    String valueField = ChartUtils.evaluateParam(paramMap.get("valuefield"), variableMap);
    DefaultPieDataset dataset = createDataset(dataList, nameField, valueField);

    String title = ChartUtils.evaluateParam(paramMap.get("title"), variableMap);

    boolean legend =
        paramMap.get("legend") == null
            ? true
            : "true"
                .equals(
                    ChartUtils.evaluateParam(paramMap.get("legend"), variableMap).toLowerCase());

    JFreeChart chart;
    if (ChartConstants.TYPE_PIE3D.equals(type))
      chart =
          ChartFactory.createPieChart3D(
              title, // 图表标题
              dataset, // 数据集
              legend, // 是否显示图例
              false, // 是否生成工具
              false // 是否生成URL链接
              );
    else
      chart =
          ChartFactory.createPieChart(
              title, // 图表标题
              dataset, // 数据集
              legend, // 是否显示图例
              false, // 是否生成工具
              false // 是否生成URL链接
              );

    // 设置标题字体
    if (chart.getTitle() != null) chart.getTitle().setFont(titleFont);

    // 设置图例字体
    if (chart.getLegend() != null) chart.getLegend().setItemFont(legendFont);

    PiePlot pie = (PiePlot) chart.getPlot();

    //		if (pie instanceof PiePlot3D) {
    //			PiePlot3D pie3d = (PiePlot3D)pie;
    //		}

    // 设置前景透明度
    if (paramMap.get("foregroundAlpha") != null) {
      float f =
          Float.parseFloat(ChartUtils.evaluateParam(paramMap.get("foregroundAlpha"), variableMap));

      pie.setForegroundAlpha(f);
    }

    // 设置标签的最大宽度
    if (paramMap.get("maximumlabelwidth") != null) {
      float f =
          Float.parseFloat(
              ChartUtils.evaluateParam(paramMap.get("maximumlabelwidth"), variableMap));

      pie.setMaximumLabelWidth(f);
    }

    // 设置标饼上标签的标签字体
    pie.setLabelFont(labelFont);

    String labelFormat = paramMap.get("labelformat");
    if (labelFormat != null) {
      /*
       * 因为labelformat参数可能包含{0}、{1}、{2}这样的字符串,所以要通过检查'{'后面跟的字符是不是数字,来判断labelformat参数是不是表达式
       */
      int index = labelFormat.indexOf('{');

      if (index >= 0) {
        char ch = labelFormat.charAt(index + 1);

        if (!CharUtils.isAsciiNumeric(ch))
          labelFormat = ChartUtils.evaluateParam(labelFormat, variableMap);
      }

      // 设置饼上标签的显示格式,其中,0:数据名称,1:数据值,2:数据占整个百分比
      StandardPieSectionLabelGenerator generator =
          new StandardPieSectionLabelGenerator(labelFormat);
      pie.setLabelGenerator(generator);
    }

    String legendformat = paramMap.get("legendformat");
    if (legendformat != null) {
      /*
       * 因为legendformat参数可能包含{0}、{1}、{2}这样的字符串,所以要通过检查'{'后面跟的字符是不是数字,来判断legendformat参数是不是表达式
       */
      int index = legendformat.indexOf('{');

      if (index >= 0) {
        char ch = legendformat.charAt(index + 1);

        if (!CharUtils.isAsciiNumeric(ch))
          legendformat = ChartUtils.evaluateParam(legendformat, variableMap);
      }

      // 设置饼上标签的显示格式,其中,0:数据名称,1:数据值,2:数据占整个百分比
      StandardPieSectionLabelGenerator generator =
          new StandardPieSectionLabelGenerator(legendformat);
      pie.setLegendLabelGenerator(generator);
    }

    if (paramMap.get("color") != null) {
      int index = 0;

      String[] colGroups = ChartUtils.evaluateParam(paramMap.get("color"), variableMap).split(",");
      for (String colVal : colGroups) {
        Color color = ChartUtils.createColor(colVal.trim());

        pie.setSectionPaint(index++, color);
      }
    }

    // 设置饼图是圆形还是椭圆形
    if (paramMap.get("circular") != null) {
      boolean isCircular =
          "true"
              .equals(
                  ChartUtils.evaluateParam(paramMap.get("circular"), variableMap).toLowerCase());

      pie.setCircular(isCircular);
    }

    ChartUtilities.writeChartAsJPEG(os, 1, chart, width, height, null);
  }
예제 #10
0
  /** JFreeChartオブジェクトを作成する */
  private JFreeChart createChartObject(Document doc) {

    Element root = doc.getDocumentElement();
    Element chartInfo = (Element) root.getElementsByTagName("ChartInfo").item(0);
    String chartTitle =
        chartInfo.getElementsByTagName("Title").item(0).getFirstChild().getNodeValue();
    this.chartType = chartInfo.getElementsByTagName("Type").item(0).getFirstChild().getNodeValue();
    String categoryLabel =
        ((Element) chartInfo.getElementsByTagName("Category").item(0))
            .getElementsByTagName("Label")
            .item(0)
            .getFirstChild()
            .getNodeValue();

    Element firstSeries =
        (Element)
            ((Element) chartInfo.getElementsByTagName("SeriesList").item(0))
                .getElementsByTagName("Series")
                .item(0);
    String firstSeriesLabel =
        firstSeries.getElementsByTagName("Label").item(0).getFirstChild().getNodeValue();

    // データセットのリストを取得
    this.dataSetList = this.getDatasetList(doc);

    // 棒チャート(Series数に関わらない)
    if (this.chartType.equals("VerticalBar")
        || this.chartType.equals("HorizontalBar")
        || this.chartType.equals("VerticalMultiBar")
        || this.chartType.equals("HorizontalMultiBar")) {

      chart =
          ChartFactory.createBarChart(
              chartTitle,
              categoryLabel,
              firstSeriesLabel,
              (CategoryDataset) this.dataSetList.get(0),
              getLayoutFromDoc(doc),
              false,
              false,
              false);

    }

    // 3D棒チャート(Series数に関わらない)
    else if (this.chartType.equals("Vertical3D_Bar")
        || this.chartType.equals("Horizontal3D_Bar")
        || this.chartType.equals("VerticalMulti3D_Bar")
        || this.chartType.equals("HorizontalMulti3D_Bar")) {

      chart =
          ChartFactory.createBarChart3D(
              chartTitle,
              categoryLabel,
              firstSeriesLabel,
              (CategoryDataset) this.dataSetList.get(0),
              getLayoutFromDoc(doc),
              false,
              false,
              false);
    }

    // 積み上げ棒チャート
    else if ((this.chartType.equals("VerticalStackedBar"))
        || (this.chartType.equals("HorizontalStackedBar"))) {

      chart =
          ChartFactory.createStackedBarChart(
              chartTitle,
              categoryLabel,
              firstSeriesLabel,
              (CategoryDataset) this.dataSetList.get(0),
              getLayoutFromDoc(doc),
              false,
              false,
              false);

    }

    // 3D積み上げ棒チャート
    else if ((this.chartType.equals("VerticalStacked3D_Bar"))
        || (this.chartType.equals("HorizontalStacked3D_Bar"))) {

      chart =
          ChartFactory.createStackedBarChart3D(
              chartTitle,
              categoryLabel,
              firstSeriesLabel,
              (CategoryDataset) this.dataSetList.get(0),
              getLayoutFromDoc(doc),
              false,
              false,
              false);

    }

    // 折れ線チャート(Series数に関わらない)
    else if ((this.chartType.equals("Line")) || (this.chartType.equals("MultiLine"))) {

      chart =
          ChartFactory.createLineChart(
              chartTitle,
              categoryLabel,
              firstSeriesLabel,
              (CategoryDataset) this.dataSetList.get(0),
              PlotOrientation.VERTICAL,
              false,
              false,
              false);

    }

    // 面チャート(Series数に関わらない)
    else if ((this.chartType.equals("Area")) || (this.chartType.equals("MultiArea"))) {

      chart =
          ChartFactory.createAreaChart(
              chartTitle,
              categoryLabel,
              firstSeriesLabel,
              (CategoryDataset) this.dataSetList.get(0),
              PlotOrientation.VERTICAL,
              false,
              false,
              false);

    }

    // 積み上げ面チャート
    else if (this.chartType.equals("StackedArea")) {

      chart =
          ChartFactory.createStackedAreaChart(
              chartTitle,
              categoryLabel,
              firstSeriesLabel,
              (CategoryDataset) this.dataSetList.get(0),
              PlotOrientation.VERTICAL,
              false,
              false,
              false);

    }

    // 円チャート(Series数に関わらない)
    else if (this.chartType.equals("Pie")) {

      chart =
          ChartFactory.createPieChart(
              chartTitle, (PieDataset) this.dataSetList.get(0), false, false, false);

    }

    // 3D円チャート(Series数に関わらない)
    else if (this.chartType.equals("Pie_3D")) {

      chart =
          ChartFactory.createPieChart3D(
              chartTitle, (PieDataset) this.dataSetList.get(0), false, false, false);

    }

    // 複数円チャート(Series数が2以上)
    else if (this.chartType.equals("MultiPie")) {

      // 複数円チャート
      chart =
          ChartFactory.createMultiplePieChart(
              chartTitle,
              (CategoryDataset) this.dataSetList.get(0),
              TableOrder.BY_ROW,
              false,
              false,
              false);
    }

    return chart;
  }
예제 #11
0
  public static String getSimplePieChart(Map dataSource, String objectName, HttpSession session)
      throws Throwable {
    DefaultPieDataset dataset = new DefaultPieDataset();

    Element chartObject =
        XMLHandler.getElementByAttribute(getChartObjectList(), "name", objectName);

    String title = chartObject.getAttributeValue("title");

    int width = Integer.parseInt(chartObject.getAttributeValue("width"));
    int height = Integer.parseInt(chartObject.getAttributeValue("height"));

    Element LabelKeys = chartObject.getChild("Labels");
    Element ValueKeys = chartObject.getChild("Values");

    String valueKey = ValueKeys.getText();
    String valueType = ValueKeys.getAttributeValue("type");
    List labelKeys = LabelKeys.getChildren("Label");
    String labelKey = LabelKeys.getText();

    if (valueType.equalsIgnoreCase("number")) {
      for (int i = 0; i < dataSource.size(); i++) {
        Map rec = (Map) dataSource.get("ROW" + i);
        Number value = (Number) rec.get(valueKey);
        String label;
        if (labelKeys.isEmpty()) {
          label = DataFilter.show(rec, labelKey);
        } else {
          label = ((Element) labelKeys.get(i)).getText();
        }
        dataset.setValue(label, value);
      }
    } else {
      for (int i = 0; i < dataSource.size(); i++) {
        Map rec = (Map) dataSource.get("ROW" + i);
        double value = (Double) rec.get(valueKey);
        String label;
        if (labelKeys.isEmpty()) {
          label = DataFilter.show(rec, labelKey);
        } else {
          label = ((Element) labelKeys.get(i)).getText();
        }
        dataset.setValue(label, value);
      }
    }

    JFreeChart chart =
        ChartFactory.createPieChart3D(
            title,
            dataset,
            chartObject.getAttribute("showLegend").getBooleanValue(),
            chartObject.getAttribute("showToolTips").getBooleanValue(),
            chartObject.getAttribute("urls").getBooleanValue());

    PiePlot3D pie3dplot = (PiePlot3D) chart.getPlot();

    float alpha = 0.7F;
    if (chartObject.getAttribute("alpha") != null) {
      alpha = chartObject.getAttribute("alpha").getFloatValue();
    }
    pie3dplot.setForegroundAlpha(alpha);

    return ServletUtilities.saveChartAsPNG(chart, width, height, null, session);
  }