Example usage for org.jfree.data.category DefaultCategoryDataset setValue

List of usage examples for org.jfree.data.category DefaultCategoryDataset setValue

Introduction

In this page you can find the example usage for org.jfree.data.category DefaultCategoryDataset setValue.

Prototype

public void setValue(double value, Comparable rowKey, Comparable columnKey) 

Source Link

Document

Adds or updates a value in the table and sends a DatasetChangeEvent to all registered listeners.

Usage

From source file:examples.audit.CoinsExample.java

/**
 * Executes the genetic algorithm to determine the minimum number of
 * coins necessary to make up the given target amount of change. The
 * solution will then be written to System.out.
 *
 * @param a_targetChangeAmount the target amount of change for which this
 * method is attempting to produce the minimum number of coins
 * @throws Exception/*  w ww. ja va2s.c  om*/
 *
 * @author Neil Rotstan
 * @author Klaus Meffert
 * @since 1.0
 */
public static void makeChangeForAmount(int a_targetChangeAmount) throws Exception {
    // Start with a DefaultConfiguration, which comes setup with the
    // most common settings.
    // -------------------------------------------------------------
    Configuration conf = new DefaultConfiguration();
    conf.setPreservFittestIndividual(true);
    // Set the fitness function we want to use, which is our
    // MinimizingMakeChangeFitnessFunction. We construct it with
    // the target amount of change passed in to this method.
    // ---------------------------------------------------------
    FitnessFunction myFunc = new CoinsExampleFitnessFunction(a_targetChangeAmount);
    conf.setFitnessFunction(myFunc);
    // Now we need to tell the Configuration object how we want our
    // Chromosomes to be setup. We do that by actually creating a
    // sample Chromosome and then setting it on the Configuration
    // object. As mentioned earlier, we want our Chromosomes to each
    // have four genes, one for each of the coin types. We want the
    // values (alleles) of those genes to be integers, which represent
    // how many coins of that type we have. We therefore use the
    // IntegerGene class to represent each of the genes. That class
    // also lets us specify a lower and upper bound, which we set
    // to sensible values for each coin type.
    // --------------------------------------------------------------
    Gene[] sampleGenes = new Gene[4];
    sampleGenes[0] = new IntegerGene(conf, 0, 3 * 10); // Quarters
    sampleGenes[1] = new IntegerGene(conf, 0, 2 * 10); // Dimes
    sampleGenes[2] = new IntegerGene(conf, 0, 1 * 10); // Nickels
    sampleGenes[3] = new IntegerGene(conf, 0, 4 * 10); // Pennies
    Chromosome sampleChromosome = new Chromosome(conf, sampleGenes);
    conf.setSampleChromosome(sampleChromosome);
    // Finally, we need to tell the Configuration object how many
    // Chromosomes we want in our population. The more Chromosomes,
    // the larger number of potential solutions (which is good for
    // finding the answer), but the longer it will take to evolve
    // the population (which could be seen as bad).
    // ------------------------------------------------------------
    conf.setPopulationSize(50);
    // Added here for demonstrating purposes is a permuting configuration.
    // It allows for evaluating which configuration could work best for
    // the given problem.
    // -------------------------------------------------------------------
    PermutingConfiguration pconf = new PermutingConfiguration(conf);
    pconf.addGeneticOperatorSlot(new CrossoverOperator(conf));
    pconf.addGeneticOperatorSlot(new MutationOperator(conf));
    pconf.addNaturalSelectorSlot(new BestChromosomesSelector(conf));
    pconf.addNaturalSelectorSlot(new WeightedRouletteSelector(conf));
    pconf.addRandomGeneratorSlot(new StockRandomGenerator());
    RandomGeneratorForTesting rn = new RandomGeneratorForTesting();
    rn.setNextDouble(0.7d);
    rn.setNextInt(2);
    pconf.addRandomGeneratorSlot(rn);
    pconf.addRandomGeneratorSlot(new GaussianRandomGenerator());
    pconf.addFitnessFunctionSlot(new CoinsExampleFitnessFunction(a_targetChangeAmount));
    Evaluator eval = new Evaluator(pconf);
    /**@todo class Evaluator:
     * input:
     *   + PermutingConfiguration
     *   + Number of evaluation runs pers config (to turn off randomness
     *     as much as possible)
     *   + output facility (data container)
     *   + optional: event subscribers
     * output:
     *   + averaged curve of fitness value thru all generations
     *   + best fitness value accomplished
     *   + average number of performance improvements for all generations
     */
    int permutation = 0;
    while (eval.hasNext()) {
        // Create random initial population of Chromosomes.
        // ------------------------------------------------
        Genotype population = Genotype.randomInitialGenotype(eval.next());
        for (int run = 0; run < 10; run++) {
            // Evolve the population. Since we don't know what the best answer
            // is going to be, we just evolve the max number of times.
            // ---------------------------------------------------------------
            for (int i = 0; i < MAX_ALLOWED_EVOLUTIONS; i++) {
                population.evolve();
                // Add current best fitness to chart.
                // ----------------------------------
                double fitness = population.getFittestChromosome().getFitnessValue();
                if (i % 3 == 0) {
                    String s = String.valueOf(i);
                    //            Number n = eval.getValue("Fitness " + permutation, s);
                    //            double d;
                    //            if (n != null) {
                    //              // calculate historical average
                    //              d = n.doubleValue() + fitness/(run+1);
                    //            }
                    //            else {
                    //              d = fitness;
                    //            }
                    eval.setValue(permutation, run, fitness, "" + permutation, s);
                    eval.storeGenotype(permutation, run, population);
                    //            eval.setValue(permutation,run,fitness, new Integer(0), s);
                }
            }
        }
        // Display the best solution we found.
        // -----------------------------------
        IChromosome bestSolutionSoFar = population.getFittestChromosome();
        System.out.println("The best solution has a fitness value of " + bestSolutionSoFar.getFitnessValue());
        System.out.println("It contained the following: ");
        System.out.println(
                "\t" + CoinsExampleFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 0) + " quarters.");
        System.out.println(
                "\t" + CoinsExampleFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 1) + " dimes.");
        System.out.println(
                "\t" + CoinsExampleFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 2) + " nickels.");
        System.out.println(
                "\t" + CoinsExampleFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 3) + " pennies.");
        System.out.println(
                "For a total of " + CoinsExampleFitnessFunction.amountOfChange(bestSolutionSoFar) + " cents in "
                        + CoinsExampleFitnessFunction.getTotalNumberOfCoins(bestSolutionSoFar) + " coins.");
        permutation++;
    }
    // Create chart: fitness values average over all permutations.
    // -----------------------------------------------------------

    // Construct JFreeChart Dataset.
    // -----------------------------
    KeyedValues2D myDataset = eval.calcAvgFitness(-1); //eval.getData();
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (int ii = 0; ii < myDataset.getColumnCount(); ii++) {
        for (int jj = 0; jj < myDataset.getRowCount(); jj++) {
            dataset.setValue(myDataset.getValue(myDataset.getRowKey(jj), myDataset.getColumnKey(ii)),
                    "Perm " + myDataset.getRowKey(jj), myDataset.getColumnKey(ii));
        }
    }
    PlotOrientation or = PlotOrientation.VERTICAL;
    JFreeChart chart = ChartFactory.createLineChart("JGAP: Evolution progress", "Evolution cycle",
            "Fitness value", dataset, or, true /*legend*/, true
            /*tooltips*/
            , false /*urls*/);
    BufferedImage image = chart.createBufferedImage(640, 480);
    FileOutputStream fo = new FileOutputStream("c:\\JGAP_chart_fitness_values.jpg");
    ChartUtilities.writeBufferedImageAsJPEG(fo, 0.7f, image);
    // Performance metrics for each single permutation.
    // ------------------------------------------------
    int maxPerm = permutation - 1;
    double avgBestFitness = 0.0d;
    int avgBestGen = 0;
    double avgAvgFitness = 0.0d;
    double avgAvgDiv = 0.0d;
    double avgAvgBestD = 0.0d;
    for (int i = 0; i < maxPerm; i++) {
        //      myDataset = eval.calcAvgFitness(i);
        Evaluator.GenotypeDataAvg dataAvg = eval.calcPerformance(i);
        System.err.println("-----------------------------");
        System.err.println("Perm " + i);
        System.err.println("Best Fitness " + dataAvg.bestFitnessValue);
        System.err.println(" Generation  " + dataAvg.bestFitnessValueGeneration);
        System.err.println(" BestFit/Gen " + dataAvg.bestFitnessValue / dataAvg.bestFitnessValueGeneration);
        System.err.println("Avg. Fitness " + dataAvg.avgFitnessValue);
        System.err.println("Avg. Div.    " + dataAvg.avgDiversityFitnessValue);
        System.err.println("Avg. BestD   " + dataAvg.avgBestDeltaFitnessValue);
        avgBestFitness += dataAvg.bestFitnessValue;
        avgBestGen += dataAvg.bestFitnessValueGeneration;
        avgAvgFitness += dataAvg.avgFitnessValue;
        avgAvgDiv += dataAvg.avgDiversityFitnessValue;
        avgAvgBestD += dataAvg.avgBestDeltaFitnessValue;
    }
    // Performance metrics for all permutations.
    // -----------------------------------------
    System.err.println("\nOverall Statistics for all permutations");
    System.err.println("----------------------------------------");
    System.err.println("Avg. Best Fitness     " + avgBestFitness / maxPerm);
    System.err.println("Avg. Best Generation  " + avgBestGen / maxPerm);
    System.err.println("Avg. Avg. Fitness     " + avgAvgFitness / maxPerm);
    System.err.println("Avg. Avg. Diversity   " + avgAvgDiv / maxPerm);
    System.err.println("Avg. Avg. BestD       " + avgAvgBestD / maxPerm);
    // Create chart: performance metrics for all permutations.
    // -----------------------------------------------------------
    dataset = new DefaultCategoryDataset();
    for (int ii = 0; ii < myDataset.getColumnCount(); ii++) {
        for (int jj = 0; jj < myDataset.getRowCount(); jj++) {
            dataset.setValue(myDataset.getValue(myDataset.getRowKey(jj), myDataset.getColumnKey(ii)),
                    myDataset.getRowKey(jj), myDataset.getColumnKey(ii));
        }
    }
    chart = ChartFactory.createLineChart("JGAP: Evolution progress", "Evolution cycle", "Fitness value",
            dataset, or, true /*legend*/, true
            /*tooltips*/
            , false /*urls*/);
    image = chart.createBufferedImage(640, 480);
    fo = new FileOutputStream("c:\\JGAP_chart_fitness_values_1.jpg");
    ChartUtilities.writeBufferedImageAsJPEG(fo, 0.7f, image);
}

From source file:lectorarchivos.VerCSV.java

public static void mostrarGrafica(JTable jTableInfoCSV) {
    //Fuente de datos
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    //Recorremos la columna del consumo de la tabla
    for (int i = jTableInfoCSV.getRowCount() - 1; i >= 0; i--) {
        if (Double.parseDouble(jTableInfoCSV.getValueAt(i, 4).toString()) > 0)
            dataset.setValue(Double.parseDouble(jTableInfoCSV.getValueAt(i, 4).toString()), "Consumo",
                    jTableInfoCSV.getValueAt(i, 0).toString());
    }/* w ww  . ja  v a2s .c  o  m*/

    //Creando el grfico
    JFreeChart chart = ChartFactory.createBarChart3D("Consumo", "Fecha", "Consumo", dataset,
            PlotOrientation.VERTICAL, true, true, false);
    chart.setBackgroundPaint(Color.cyan);
    chart.getTitle().setPaint(Color.black);
    chart.setBackgroundPaint(Color.white);
    chart.removeLegend();

    //Cambiar color de barras
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    BarRenderer barRenderer = (BarRenderer) plot.getRenderer();
    barRenderer.setSeriesPaint(0, Color.decode("#5882FA"));

    // Mostrar Grafico
    ChartFrame frame = new ChartFrame("CONSUMO", chart);
    frame.pack();
    frame.getChartPanel().setMouseZoomable(false);
    frame.setVisible(true);

    panel.add(frame);

}

From source file:org.sipfoundry.sipxconfig.site.cdr.CdrReports.java

private static Image createExtensionsChartImage(List<CdrGraphBean> extensions, String xAxisLabel,
        String yAxisLabel) {// ww  w. j a va  2s.c  om
    // Create a dataset...
    DefaultCategoryDataset data = new DefaultCategoryDataset();

    // Fill dataset with beans data
    for (CdrGraphBean extension : extensions) {
        data.setValue(extension.getCount(), extension.getKey(), extension.getKey());
    }

    // Create a chart with the dataset
    JFreeChart barChart = ChartFactory.createBarChart3D(EMPTY_TITLE, xAxisLabel, yAxisLabel, data,
            PlotOrientation.VERTICAL, true, true, true);
    barChart.setBackgroundPaint(Color.lightGray);
    barChart.getTitle().setPaint(Color.BLACK);
    CategoryPlot p = barChart.getCategoryPlot();
    p.setRangeGridlinePaint(Color.red);

    // Create and return the image with the size specified in the XML design
    return barChart.createBufferedImage(500, 220, BufferedImage.TYPE_INT_RGB, null);
}

From source file:utils.ChartUtils.java

/**
 * Update IR bar chart/*w w w. ja v a 2s .c  o  m*/
 * 
 * @param labelsByFrequency Labels ordered by frequency
 * @param IR Imbalance Ratio values
 * @param cp CategoryPlot
 */
public static void updateIRBarChart(ImbalancedFeature[] labelsByFrequency, double[] IR, CategoryPlot cp) {
    DefaultCategoryDataset myData = new DefaultCategoryDataset();

    double prob = 0;

    labelsByFrequency = MetricUtils.sortByFrequency(labelsByFrequency);

    double sum = 0.0;
    for (int i = labelsByFrequency.length - 1; i >= 0; i--) {
        prob = IR[i];
        sum += prob;
        myData.setValue(prob, labelsByFrequency[i].getName(), " ");
    }

    cp.setDataset(myData);

    // add mean mark
    sum = sum / labelsByFrequency.length;
    Marker meanMark = new ValueMarker(sum);
    meanMark.setPaint(Color.red);
    meanMark.setLabelFont(new Font("SansSerif", Font.BOLD, 12));
    meanMark.setLabel("                        Mean: " + MetricUtils.truncateValue(sum, 3));
    cp.addRangeMarker(meanMark);

    //Add Imbalance limit mark
    Marker limitMark = new ValueMarker(1.5);
    limitMark.setPaint(Color.black);
    limitMark.setLabelFont(new Font("SansSerif", Font.BOLD, 12));

    if ((sum < 1.3) || (sum > 1.7)) {
        limitMark.setLabel("                                                Imbalance limit (IR=1.5)");
    }
    cp.addRangeMarker(limitMark);
}

From source file:org.sipfoundry.sipxconfig.site.cdr.CdrReports.java

private static Image createMinutesOutgoingCallsChartImage(List<CdrMinutesGraphBean> minutesOutgoingCalls,
        String xAxisLabel, String yAxisLabel) {
    // Create a dataset...
    DefaultCategoryDataset data = new DefaultCategoryDataset();

    // Fill dataset with beans data
    for (CdrMinutesGraphBean minutesOutgoingCall : minutesOutgoingCalls) {
        data.setValue(minutesOutgoingCall.getMinutes() / 60000, minutesOutgoingCall.getExtension(),
                minutesOutgoingCall.getExtension());
    }//  ww w.j  av a2 s .  c o  m

    // Create a chart with the dataset
    JFreeChart barChart = ChartFactory.createBarChart3D(EMPTY_TITLE, xAxisLabel, yAxisLabel, data,
            PlotOrientation.VERTICAL, true, true, true);
    barChart.setBackgroundPaint(Color.lightGray);
    barChart.getTitle().setPaint(Color.BLACK);
    CategoryPlot p = barChart.getCategoryPlot();
    p.setRangeGridlinePaint(Color.red);

    // Create and return the image with the size specified in the XML design
    return barChart.createBufferedImage(500, 220, BufferedImage.TYPE_INT_RGB, null);
}

From source file:utils.ChartUtils.java

/**
 * Update values of a bar chart// www .ja  v a 2 s .c o m
 * 
 * @param labelsByFreq Labels ordered by frequency
 * @param nInstances Number of instances
 * @param cp CategoryPlot
 */
public static void updateValuesBarChart(ImbalancedFeature[] labelsByFreq, int nInstances, CategoryPlot cp) {
    DefaultCategoryDataset data = new DefaultCategoryDataset();

    double prob;

    labelsByFreq = MetricUtils.sortByFrequency(labelsByFreq);

    double sum = 0.0;
    for (int i = 0; i < labelsByFreq.length; i++) {
        prob = labelsByFreq[i].getAppearances() * 1.0 / nInstances;
        sum += prob;

        data.setValue(prob, labelsByFreq[i].getName(), " ");
    }

    cp.setDataset(data);

    // add mean mark
    sum = sum / labelsByFreq.length;
    Marker start = new ValueMarker(sum);
    start.setPaint(Color.red);
    start.setLabelFont(new Font("SansSerif", Font.BOLD, 12));
    start.setLabel("                        Mean: " + MetricUtils.truncateValue(sum, 3));
    cp.addRangeMarker(start);
}

From source file:utils.ChartUtils.java

/**
 * Update line chart/*from  w w w . jav  a2s.  co  m*/
 * 
 * @param nInstances Number of instances
 * @param cp CategoryPlot
 * @param labelsetsByFrequency Labelsets ordered by frequency
 */
public static void updateLineChart(int nInstances, CategoryPlot cp,
        HashMap<Integer, Integer> labelsetsByFrequency) {
    DefaultCategoryDataset data = new DefaultCategoryDataset();

    double prob;

    int max = maxKey(labelsetsByFrequency);

    for (int i = 0; i <= max; i++) {
        int currentFreq = 0;
        if (labelsetsByFrequency.get(i) != null) {
            currentFreq = labelsetsByFrequency.get(i);
        }

        prob = currentFreq * 1.0 / nInstances;

        if (prob == 0.0) {
            data.setValue(0, "Label-Combination: ", Integer.toString(i));
        } else {
            data.setValue(prob, "Label-Combination: ", Integer.toString(i));
        }

    }
    cp.setDataset(data);

    if (max > 30) {
        cp.getDomainAxis().setTickLabelsVisible(false);
    } else {
        cp.getDomainAxis().setTickLabelsVisible(true);
    }
}

From source file:com.athena.chameleon.engine.utils.PDFWriterUtil.java

/**
 * // ww w .  j a v  a 2s .c  om
 * chart 
 *
 * @param section chart   section ?
 * @param e chart   element
 * @throws Exception
 */
public static void setChart(PdfWriter writer, Section section, Element e) throws Exception {

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    for (Element e1 : e.getChildren()) {
        if (!e1.getChild("column").getText().equals(FileType.DIRECTORY.toString())
                && !e1.getChild("column").getText().equals(FileType.SUM.toString())) {
            dataset.setValue(Integer.parseInt(e1.getChild("value").getText()), e.getAttributeValue("title"),
                    e1.getChild("column").getText());
        }
    }

    JFreeChart chart = ChartFactory.createBarChart3D(e.getAttributeValue("title"), "", "", dataset,
            PlotOrientation.VERTICAL, false, true, false);

    CategoryPlot plot = chart.getCategoryPlot();
    java.awt.Font labelFont = chart.getCategoryPlot().getDomainAxis().getLabelFont();
    plot.getDomainAxis().setLabelFont(new java.awt.Font(labelFont.getName(), Font.NORMAL, 6));
    plot.getDomainAxis().setTickLabelFont(new java.awt.Font(labelFont.getName(), Font.NORMAL, 6));

    PdfContentByte cb = writer.getDirectContent();
    PdfTemplate bar = cb.createTemplate(500, 150);
    Graphics2D g2d2 = new PdfGraphics2D(bar, 500, 150);
    Rectangle2D r2d2 = new Rectangle2D.Double(0, 0, 500, 150);
    chart.draw(g2d2, r2d2);
    g2d2.dispose();

    Image image = Image.getInstance(bar);
    image.setAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
    section.add(image);
}

From source file:examples.MinimizingMakeChangeWithChart.java

/**
 * Executes the genetic algorithm to determine the minimum number of
 * coins necessary to make up the given target amount of change. The
 * solution will then be written to System.out.
 *
 * @param a_targetChangeAmount the target amount of change for which this
 * method is attempting to produce the minimum number of coins
 * @param a_chartDirectory directory to put the chart in
 *
 * @throws Exception// w ww  . j av a2s .c  om
 *
 * @author Neil Rotstan
 * @author Klaus Meffert
 * @since 1.0
 */
public static void makeChangeForAmount(int a_targetChangeAmount, String a_chartDirectory) throws Exception {
    // Start with a DefaultConfiguration, which comes setup with the
    // most common settings.
    // -------------------------------------------------------------
    Configuration conf = new DefaultConfiguration();
    conf.setPreservFittestIndividual(true);
    conf.setKeepPopulationSizeConstant(false);
    // Set the fitness function we want to use, which is our
    // MinimizingMakeChangeFitnessFunction. We construct it with
    // the target amount of change passed in to this method.
    // ---------------------------------------------------------
    FitnessFunction myFunc = new MinimizingMakeChangeFitnessFunction(a_targetChangeAmount);
    //    conf.setFitnessFunction(myFunc);
    conf.setBulkFitnessFunction(new BulkFitnessOffsetRemover(myFunc));
    // Optionally, this example is working with DeltaFitnessEvaluator.
    // See MinimizingMakeChangeFitnessFunction for details!
    // ---------------------------------------------------------------
    //    conf.setFitnessEvaluator(new DeltaFitnessEvaluator());

    // Now we need to tell the Configuration object how we want our
    // Chromosomes to be setup. We do that by actually creating a
    // sample Chromosome and then setting it on the Configuration
    // object. As mentioned earlier, we want our Chromosomes to each
    // have four genes, one for each of the coin types. We want the
    // values (alleles) of those genes to be integers, which represent
    // how many coins of that type we have. We therefore use the
    // IntegerGene class to represent each of the genes. That class
    // also lets us specify a lower and upper bound, which we set
    // to sensible values for each coin type.
    // --------------------------------------------------------------
    Gene[] sampleGenes = new Gene[4];
    sampleGenes[0] = new IntegerGene(conf, 0, 3 * 10); // Quarters
    sampleGenes[1] = new IntegerGene(conf, 0, 2 * 10); // Dimes
    sampleGenes[2] = new IntegerGene(conf, 0, 1 * 10); // Nickels
    sampleGenes[3] = new IntegerGene(conf, 0, 4 * 10); // Pennies
    IChromosome sampleChromosome = new Chromosome(conf, sampleGenes);
    conf.setSampleChromosome(sampleChromosome);
    // Finally, we need to tell the Configuration object how many
    // Chromosomes we want in our population. The more Chromosomes,
    // the larger number of potential solutions (which is good for
    // finding the answer), but the longer it will take to evolve
    // the population (which could be seen as bad).
    // ------------------------------------------------------------
    conf.setPopulationSize(80);
    // JFreeChart: setup
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    PlotOrientation or = PlotOrientation.VERTICAL;
    // Create random initial population of Chromosomes.
    // ------------------------------------------------
    Genotype population = Genotype.randomInitialGenotype(conf);
    // Evolve the population. Since we don't know what the best answer
    // is going to be, we just evolve the max number of times.
    // ---------------------------------------------------------------
    for (int i = 0; i < MAX_ALLOWED_EVOLUTIONS; i++) {
        population.evolve();
        // JFreeChart: add current best fitness to chart
        double fitness = population.getFittestChromosome().getFitnessValue();
        if (i % 3 == 0) {
            String s = String.valueOf(i);
            dataset.setValue(fitness, "Fitness", s);
        }
    }
    // Display the best solution we found.
    // -----------------------------------
    IChromosome bestSolutionSoFar = population.getFittestChromosome();
    System.out.println("The best solution has a fitness value of " + bestSolutionSoFar.getFitnessValue());
    System.out.println("It contained the following: ");
    System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 0)
            + " quarters.");
    System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 1)
            + " dimes.");
    System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 2)
            + " nickels.");
    System.out.println("\t" + MinimizingMakeChangeFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 3)
            + " pennies.");
    System.out.println("For a total of " + MinimizingMakeChangeFitnessFunction.amountOfChange(bestSolutionSoFar)
            + " cents in " + MinimizingMakeChangeFitnessFunction.getTotalNumberOfCoins(bestSolutionSoFar)
            + " coins.");
    // JFreeChart: Create chart
    JFreeChart chart = ChartFactory.createLineChart("JGAP: Evolution progress", "Evolution cycle",
            "Fitness value", dataset, or, true /*legend*/, true
            /*tooltips*/
            , false /*urls*/);
    BufferedImage image = chart.createBufferedImage(640, 480);
    String imagefile = "chart.jpg";
    FileOutputStream fo = new FileOutputStream(a_chartDirectory + imagefile);
    ChartUtilities.writeBufferedImageAsJPEG(fo, 0.7f, image);
    System.out.println("Chart written to image file " + a_chartDirectory + imagefile);
}

From source file:org.posterita.businesslogic.performanceanalysis.CustomPOSReportManager.java

public static BarChart generateBarChart(Properties ctx, String title, String subtitle, int account_id,
        Timestamp fromDate, Timestamp toDate, String salesGroup, String priceQtyFilter)
        throws OperationException {
    BarChart barChart = new BarChart();
    barChart.setTitle(title);/*from  www  .ja  va 2 s.c o  m*/
    barChart.setSubtitle(subtitle);
    //barChart.getDataSetFromSQL(barChartSQL);

    String barChartSQL = SalesAnalysisReportManager.getBarChartDataSetSQL(ctx, account_id, fromDate, toDate,
            salesGroup);
    ArrayList<Object[]> list = ReportManager.getReportData(ctx, barChartSQL, true);
    DefaultCategoryDataset categoryDataset = new DefaultCategoryDataset();

    Object[] header = list.remove(0);
    String grouping = header[0] + "";
    String yLabel = null;

    if (priceQtyFilter.equalsIgnoreCase(Constants.PRICE)) {
        String currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol();

        //against price
        for (Object[] obj : list) {
            String name = (String) obj[0];
            BigDecimal price = (BigDecimal) obj[1];

            categoryDataset.setValue(price, grouping, name);
            yLabel = "Value (" + currency + ")";
        }
    } else {
        //against qty
        for (Object[] obj : list) {
            String name = (String) obj[0];
            BigDecimal qty = (BigDecimal) obj[2];

            categoryDataset.setValue(qty, grouping, name);
            yLabel = "Quantity";
        }
    }

    //xLabel = grouping;

    //---------------------------------------------------------------------------------
    barChart.setDataset(categoryDataset);
    barChart.setIntegerTickUnits(true);

    //CategoryItemRenderer itemRender = barChart.getChart().getPlot();
    //itemRender.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());      

    barChart.setYLabel(yLabel);
    //barChart.setXLabel(xLabel);
    barChart.setShowLabels(true);
    barChart.getChart().setBackgroundPaint(Color.white);

    return barChart;
}