/**
  * 创建一个饼图表的数据集
  *
  * @return
  */
 private PieDataset getPieDataset() {
   DefaultPieDataset dataset = new DefaultPieDataset();
   dataset.setValue("JAVA从入门到精通(第2版)", 500);
   dataset.setValue("视频学JAVA", 800);
   dataset.setValue("JAVA全能速查宝典", 1000);
   return dataset;
 }
Exemple #2
0
  /** Some checks for the getLegendItems() method. */
  @Test
  public void testGetLegendItems() {
    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("Item 1", 1.0);
    dataset.setValue("Item 2", 2.0);
    dataset.setValue("Item 3", 0.0);
    dataset.setValue("Item 4", null);

    PiePlot plot = new PiePlot(dataset);
    plot.setIgnoreNullValues(false);
    plot.setIgnoreZeroValues(false);
    List<LegendItem> items = plot.getLegendItems();
    assertEquals(4, items.size());

    // check that null items are ignored if requested
    plot.setIgnoreNullValues(true);
    items = plot.getLegendItems();
    assertEquals(3, items.size());

    // check that zero items are ignored if requested
    plot.setIgnoreZeroValues(true);
    items = plot.getLegendItems();
    assertEquals(2, items.size());

    // check that negative items are always ignored
    dataset.setValue("Item 5", -1.0);
    items = plot.getLegendItems();
    assertEquals(2, items.size());
  }
 private static PieDataset createDataset(StateBean sb) {
   DefaultPieDataset localDefaultPieDataset = new DefaultPieDataset();
   localDefaultPieDataset.setValue("正常", sb.getOk());
   localDefaultPieDataset.setValue("危险", sb.getWarn());
   localDefaultPieDataset.setValue("错误", sb.getError());
   localDefaultPieDataset.setValue("禁止", sb.getDisable());
   localDefaultPieDataset.setValue("无监测数据", sb.getBad());
   return localDefaultPieDataset;
 }
 private PieDataset createDataset(StateBean sb) {
   DefaultPieDataset localDefaultPieDataset = new DefaultPieDataset();
   localDefaultPieDataset.setValue("Õý³£", sb.getOk());
   localDefaultPieDataset.setValue("¾¯¸æ", sb.getWarn());
   localDefaultPieDataset.setValue("´íÎó", sb.getError());
   localDefaultPieDataset.setValue("½ûÖ¹", sb.getDisable());
   localDefaultPieDataset.setValue("Í£Ö¹", sb.getBad());
   return localDefaultPieDataset;
 }
 private PieDataset createSampleDataSet() {
   final DefaultPieDataset result = new DefaultPieDataset();
   result.setValue("Java", new Double(43.2));
   result.setValue("Visual Basic", new Double(10.0));
   result.setValue("C/C++", new Double(17.5));
   result.setValue("PHP", new Double(32.5));
   result.setValue("Perl", new Double(1.0));
   return result;
 }
 private static PieDataset createDataset() {
   DefaultPieDataset defaultpiedataset = new DefaultPieDataset();
   defaultpiedataset.setValue("Network", new Double(43.200000000000003D));
   defaultpiedataset.setValue("Database", new Double(10D));
   defaultpiedataset.setValue("Operating System", new Double(17.5D));
   defaultpiedataset.setValue("Software Engineering", new Double(32.5D));
   defaultpiedataset.setValue("Programming Language", new Double(12.5D));
   return defaultpiedataset;
 }
Exemple #7
0
  public static DefaultPieDataset getPieDataset(String chartName, DBSeerDataSet dataset) {
    StatisticalPackageRunner runner = DBSeerGUI.runner;

    runner.eval(
        "[title legends Xdata Ydata Xlabel Ylabel timestamp] = plotter.plot" + chartName + ";");

    String title = runner.getVariableString("title");
    Object[] legends = (Object[]) runner.getVariableCell("legends");
    Object[] xCellArray = (Object[]) runner.getVariableCell("Xdata");
    Object[] yCellArray = (Object[]) runner.getVariableCell("Ydata");
    String xLabel = runner.getVariableString("Xlabel");
    String yLabel = runner.getVariableString("Ylabel");
    timestamp = runner.getVariableDouble("timestamp");

    DefaultPieDataset pieDataSet = new DefaultPieDataset();

    int numLegends = legends.length;
    int numXCellArray = xCellArray.length;
    int numYCellArray = yCellArray.length;
    int dataCount = 0;

    if (numXCellArray != numYCellArray) {
      JOptionPane.showMessageDialog(
          null,
          "The number of X dataset and Y dataset does not match.",
          "The number of X dataset and Y dataset does not match.",
          JOptionPane.ERROR_MESSAGE);
      return null;
    }

    final java.util.List<String> transactionTypeNames = dataset.getTransactionTypeNames();

    for (int i = 0; i < numYCellArray; ++i) {
      double[] xArray = (double[]) xCellArray[i];
      runner.eval("yArraySize = size(Ydata{" + (i + 1) + "});");
      runner.eval("yArray = Ydata{" + (i + 1) + "};");
      double[] yArraySize = runner.getVariableDouble("yArraySize");
      double[] yArray = runner.getVariableDouble("yArray");

      int xLength = xArray.length;
      int row = (int) yArraySize[0];
      int col = (int) yArraySize[1];

      for (int c = 0; c < col; ++c) {
        if (c < transactionTypeNames.size()) {
          String name = transactionTypeNames.get(c);
          if (!name.isEmpty()) {
            pieDataSet.setValue(name, yArray[c]);
          } else {
            pieDataSet.setValue("Transaction Type " + (c + 1), yArray[c]);
          }
        }
      }
    }

    return pieDataSet;
  }
Exemple #8
0
 /**
  * Creates a sample dataset.
  *
  * @return a sample dataset.
  */
 private static DefaultPieDataset createDataset() {
   DefaultPieDataset dataset = new DefaultPieDataset();
   dataset.setValue("Section A", new Double(43.2));
   dataset.setValue("Section B", new Double(10.0));
   dataset.setValue("Section C", new Double(27.5));
   dataset.setValue("Section D", new Double(17.5));
   dataset.setValue("Section E", new Double(11.0));
   dataset.setValue("Section F", new Double(19.4));
   return dataset;
 }
 /**
  * Creates a sample dataset.
  *
  * @return A sample dataset.
  */
 private static PieDataset createDataset() {
   DefaultPieDataset dataset = new DefaultPieDataset();
   dataset.setValue("One", new Double(43.2));
   dataset.setValue("Two", new Double(10.0));
   dataset.setValue("Three", new Double(27.5));
   dataset.setValue("Four", new Double(17.5));
   dataset.setValue("Five", new Double(11.0));
   dataset.setValue("Six", new Double(19.4));
   return dataset;
 }
 private static PieDataset createDataset() {
   DefaultPieDataset localDefaultPieDataset = new DefaultPieDataset();
   localDefaultPieDataset.setValue("One", new Double(43.200000000000003D));
   localDefaultPieDataset.setValue("Two", new Double(10.0D));
   localDefaultPieDataset.setValue("Three", new Double(27.5D));
   localDefaultPieDataset.setValue("Four", new Double(17.5D));
   localDefaultPieDataset.setValue("Five", new Double(11.0D));
   localDefaultPieDataset.setValue("Six", new Double(19.399999999999999D));
   return localDefaultPieDataset;
 }
 public MouseListenerDemo1(String s) {
   super(s);
   DefaultPieDataset defaultpiedataset = new DefaultPieDataset();
   defaultpiedataset.setValue("Java", new Double(43.200000000000003D));
   defaultpiedataset.setValue("Visual Basic", new Double(0.0D));
   defaultpiedataset.setValue("C/C++", new Double(17.5D));
   org.jfree.chart.JFreeChart jfreechart =
       ChartFactory.createPieChart("Pie Chart Demo 1", defaultpiedataset, true, true, false);
   ChartPanel chartpanel = new ChartPanel(jfreechart, false, false, false, false, false);
   chartpanel.addChartMouseListener(this);
   chartpanel.setPreferredSize(new Dimension(500, 270));
   setContentPane(chartpanel);
 }
 /** Confirm that cloning works. */
 public void testCloning() {
   DefaultPieDataset d1 = new DefaultPieDataset();
   d1.setValue("V1", new Integer(1));
   d1.setValue("V2", null);
   d1.setValue("V3", new Integer(3));
   DefaultPieDataset d2 = null;
   try {
     d2 = (DefaultPieDataset) d1.clone();
   } catch (CloneNotSupportedException e) {
     System.err.println("Failed to clone.");
   }
   assertTrue(d1 != d2);
   assertTrue(d1.getClass() == d2.getClass());
   assertTrue(d1.equals(d2));
 }
 // create data set for JFreeChart pie chart
 private PieDataset createChartDataSet(
     double proportion1, double proportion2, String key1, String key2) {
   DefaultPieDataset dataSet = new DefaultPieDataset();
   dataSet.setValue(key1, proportion1);
   dataSet.setValue(key2, proportion2);
   return dataSet;
 }
 private static PieDataset createDataset(String[] name, double[] number) {
   DefaultPieDataset result = new DefaultPieDataset();
   for (int i = 0; i < name.length; i++) {
     result.setValue(name[i], number[i]);
   }
   return result;
 }
  /**
   * 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);
    }
  }
Exemple #16
0
  /** Create dataset. */
  private PieDataset createDataset() {
    DefaultPieDataset dataset = new DefaultPieDataset();
    Map<Comparable<?>, Double> values = data.getValues();

    for (Comparable<?> key : values.keySet()) {
      dataset.setValue(key, values.get(key));
    }

    return dataset;
  }
 /**
  * Description:
  *
  * @param view
  */
 public NodeStatusController(NodeStatusPanel view) {
   super();
   this.view = view;
   dataset = new DefaultPieDataset();
   StateLongTypeViz[] states = StateLongTypeViz.values();
   for (int i = 0; i < states.length; i++) {
     dataset.setValue(states[i].getName(), 0);
   }
   view.setDataset(dataset, StateLongTypeViz.colors);
 }
  public DefaultPieDataset getDataSet() {

    DefaultPieDataset dataset = new DefaultPieDataset();

    for (int i = 0; i < this.collect.size(); i++) {
      dataset.setValue(this.collect.get(i).getKey(), this.collect.get(i).getValue());
    }

    return dataset;
  }
Exemple #19
0
 @Override
 protected Dataset getDataset() {
   DefaultPieDataset result = new DefaultPieDataset();
   for (String key : keySet) {
     List<V> values = getDataRow(key);
     for (int i = 0; i < values.size(); i++) {
       result.setValue(getHeader(i), (Number) values.get(i));
     }
   }
   return result;
 }
 public static JPanel createCustomDemoPanel(Map<String, Double> map) {
   // set model
   DefaultPieDataset defaultpiedataset = new DefaultPieDataset();
   for (String key : map.keySet()) {
     defaultpiedataset.setValue(key, map.get(key));
   }
   // assign to view
   JFreeChart jfreechart = createChart(createDataset());
   Rotator rotator = new Rotator((PiePlot3D) jfreechart.getPlot());
   rotator.start();
   return new ChartPanel(jfreechart);
 }
 /** Some tests for the clear() method. */
 public void testClear() {
   DefaultPieDataset d = new DefaultPieDataset();
   d.addChangeListener(this);
   // no event is generated if the dataset is already empty
   d.clear();
   assertNull(this.lastEvent);
   d.setValue("A", 1.0);
   assertEquals(1, d.getItemCount());
   this.lastEvent = null;
   d.clear();
   assertNotNull(this.lastEvent);
   assertEquals(0, d.getItemCount());
 }
  /**
   * Herramientas Mano de Obra Materiales Compras Gastos Varios
   *
   * @return
   */
  public JFreeChart createGraph() {
    DefaultPieDataset dataset = new DefaultPieDataset();

    if (obra != null && obra.getEjecucion() != null) {
      Ejecucion ejec = obra.getEjecucion();
      // Herramientas
      double montoHerramientas = calcularMontoHerramientas(ejec);
      dataset.setValue("Herramientas [$" + montoHerramientas + "]", montoHerramientas);
      // Mano de Obra
      double montoManoObra = calcularMontoManoObra(ejec);
      dataset.setValue("Mano de Obra [$" + montoManoObra + "]", montoManoObra);
      // Materiales
      double montoMateriales = calcularMontoMateriales(ejec);
      dataset.setValue("Materiales [$" + montoMateriales + "]", montoMateriales);
      // Alquileres/Compras
      double montoAlqComp = calcularMontoAlqComp(ejec);
      dataset.setValue("Alquileres/Compras [$" + montoAlqComp + "]", montoAlqComp);
      // Gastos Varios
      double montoGastosVarios = calcularMontoGastosVarios(ejec);
      dataset.setValue("Gastos Varios [$" + montoGastosVarios + "]", montoGastosVarios);
    }
    return createGraphObject(dataset);
  }
Exemple #23
0
  /** Draws a pie chart where the label generator returns null. */
  @Test
  public void testDrawWithNullLegendLabels() {
    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("L1", 12.0);
    dataset.setValue("L2", 11.0);
    JFreeChart chart = ChartFactory.createPieChart("Test", dataset);
    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setLegendLabelGenerator(new NullLegendLabelGenerator());

    BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null);
    g2.dispose();
  }
Exemple #24
0
  private void taxPie(
      Rectangle rct, double totalValue, double tax, String taxLabel, String netLabel) {
    double taxPercent = (tax / totalValue) * 100;
    double netValuePercent = 100 - taxPercent;

    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue(taxLabel, taxPercent);
    dataset.setValue(netLabel, netValuePercent);

    PiePlot3D plot = new PiePlot3D(dataset);
    plot.setLabelGenerator(new StandardPieItemLabelGenerator());
    plot.setInsets(new Insets(0, 5, 5, 5));
    plot.setToolTipGenerator(new CustomToolTipGenerator());
    plot.setLabelGenerator(new CustomLabelGenerator());
    plot.setSectionPaint(0, new Color(pgRed));
    plot.setSectionPaint(1, new Color(pgGreen));
    plot.setForegroundAlpha(.6f);
    plot.setOutlinePaint(Color.white);
    plot.setBackgroundPaint(Color.white);

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

    chart.setBackgroundPaint(Color.white);
    chart.setAntiAlias(true);

    Rectangle page = rct;

    try {
      Image img =
          Image.getInstance(
              chart.createBufferedImage((int) page.getWidth(), (int) page.getHeight()), null);
      drawDiagram(img, rct, 0, 72);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
  /** Serialize an instance, restore it, and check for equality. */
  public void testSerialization() {

    DefaultPieDataset d1 = new DefaultPieDataset();
    d1.setValue("C1", new Double(234.2));
    d1.setValue("C2", null);
    d1.setValue("C3", new Double(345.9));
    d1.setValue("C4", new Double(452.7));

    DefaultPieDataset d2 = null;

    try {
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      ObjectOutput out = new ObjectOutputStream(buffer);
      out.writeObject(d1);
      out.close();

      ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
      d2 = (DefaultPieDataset) in.readObject();
      in.close();
    } catch (Exception e) {
      System.out.println(e.toString());
    }
    assertEquals(d1, d2);
  }
Exemple #26
0
  public static void main(String[] args) {
    // Create a simple pie chart
    DefaultPieDataset pieDataset = new DefaultPieDataset();
    pieDataset.setValue("Boom Server", new Integer(30));
    pieDataset.setValue("Next Reports", new Integer(33));
    pieDataset.setValue("ReMinder", new Integer(37));
    JFreeChart chart = ChartFactory.createPieChart("Project Hours", pieDataset, true, true, false);
    chart.setBackgroundPaint(Color.WHITE);

    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setStartAngle(330);

    // Specify the colors here
    Color[] colors = {Color.blue, Color.yellow, Color.green, Color.red, Color.ORANGE};
    PieRenderer renderer = new PieRenderer(colors);
    renderer.setColor(plot, pieDataset);

    try {
      ChartUtilities.saveChartAsJPEG(new File("C:chart.jpg"), chart, 500, 300);
    } catch (Exception e) {
      System.out.println("Problem occurred creating chart.");
    }
  }
  /** Some checks for the getIndex() method. */
  public void testGetIndex() {
    DefaultPieDataset d = new DefaultPieDataset();
    d.setValue("A", 1.0);
    d.setValue("B", 2.0);
    assertEquals(0, d.getIndex("A"));
    assertEquals(1, d.getIndex("B"));
    assertEquals(-1, d.getIndex("XX"));

    boolean pass = false;
    try {
      d.getIndex(null);
    } catch (IllegalArgumentException e) {
      pass = true;
    }
    assertTrue(pass);
  }
  private PdfPCell createKPGSPieChartCell(KeyValue[] values, String title)
      throws IOException, BadElementException {
    DefaultPieDataset dataset = new DefaultPieDataset();
    for (int n = 0; n < values.length; n++) {
      dataset.setValue(values[n].getKey(), new Double(values[n].getValue()).doubleValue());
    }
    // create chart
    final JFreeChart chart =
        ChartFactory.createPieChart(
            title, // chart title
            dataset, // data
            true, // legend
            false, // tooltips
            false // urls
            );
    // customize chart
    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(java.awt.Color.WHITE);
    if (values.length > 0) {
      if (values[0].getKey().equalsIgnoreCase("?") && values.length > 1) {
        plot.setExplodePercent(values[1].getKey(), 0.2);
      } else {
        plot.setExplodePercent(values[0].getKey(), 0.2);
      }
    }
    plot.setLegendLabelGenerator(new KPGSLegendGenerator());
    plot.setLabelGenerator(new KPGSLabelGenerator(values));
    plot.setOutlineVisible(false);
    chart.setAntiAlias(true);
    LegendTitle legendTitle = (LegendTitle) chart.getSubtitle(0);
    legendTitle.setFrame(BlockBorder.NONE);
    legendTitle.setBackgroundPaint(null);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ChartUtilities.writeChartAsPNG(
        os,
        chart,
        MedwanQuery.getInstance().getConfigInt("stats.piechartwidth", 640),
        MedwanQuery.getInstance().getConfigInt("stats.piechartheight", 480));
    cell = new PdfPCell();
    cell.setColspan(50);
    cell.setImage(Image.getInstance(os.toByteArray()));
    cell.setBorder(PdfPCell.NO_BORDER);
    cell.setPaddingLeft(5);
    cell.setPaddingRight(5);
    return cell;
  }
Exemple #29
0
 /**
  * Handles actions.
  *
  * @param e the action event.
  */
 public void actionPerformed(ActionEvent e) {
   String cmd = e.getActionCommand();
   if ("BY_KEY".equals(cmd)) {
     if (!this.ascendingByKey) {
       this.dataset.sortByKeys(SortOrder.ASCENDING);
       this.ascendingByKey = true;
     } else {
       this.dataset.sortByKeys(SortOrder.DESCENDING);
       this.ascendingByKey = false;
     }
   } else if ("BY_VALUE".equals(cmd)) {
     if (!this.ascendingByValue) {
       this.dataset.sortByValues(SortOrder.ASCENDING);
       this.ascendingByValue = true;
     } else {
       this.dataset.sortByValues(SortOrder.DESCENDING);
       this.ascendingByValue = false;
     }
   } else if ("RANDOM".equals(cmd)) {
     // we create a new dataset here - that's a bit wasteful,
     // but the DefaultPieDataset will need new methods before we
     // can shuffle it 'in place'...
     List keys = new ArrayList(this.dataset.getKeys());
     Collections.shuffle(keys);
     DefaultPieDataset pd = new DefaultPieDataset();
     Iterator iterator = keys.iterator();
     while (iterator.hasNext()) {
       Comparable key = (Comparable) iterator.next();
       pd.setValue(key, this.dataset.getValue(key));
     }
     PiePlot plot = (PiePlot) this.chart.getPlot();
     plot.setDataset(pd);
     this.dataset = pd;
   } else if ("LABELS".equals(cmd)) {
     PiePlot plot = (PiePlot) this.chart.getPlot();
     boolean simple = plot.getSimpleLabels();
     if (simple) {
       plot.setInteriorGap(0.05);
       plot.setSimpleLabels(false);
     } else {
       plot.setInteriorGap(0.01);
       plot.setSimpleLabels(true);
     }
   }
 }
  public static JFreeChart generatePieChart(JSONArray IndividualPDFChart) {
    DefaultPieDataset dataSet = new DefaultPieDataset();

    for (int i = 0; i < IndividualPDFChart.size(); i++) {

      JSONObject jsonChart = IndividualPDFChart.getJSONObject(i);
      dataSet.setValue(
          jsonChart.getString(PDFConstants.PieData1),
          Double.parseDouble(jsonChart.getString(PDFConstants.PieData2)));
    }
    JFreeChart chart =
        ChartFactory.createPieChart(PDFConstants.PieChartTitle, dataSet, true, true, false);
    //        PiePlot3D plot = (PiePlot3D) chart.getPlot();
    //        plot.setStartAngle(290);
    //        plot.setDirection(Rotation.CLOCKWISE);
    //        plot.setForegroundAlpha(0.5f);
    //
    return chart;
  }