Example usage for org.jfree.chart JFreeChart createBufferedImage

List of usage examples for org.jfree.chart JFreeChart createBufferedImage

Introduction

In this page you can find the example usage for org.jfree.chart JFreeChart createBufferedImage.

Prototype

public BufferedImage createBufferedImage(int width, int height) 

Source Link

Document

Creates and returns a buffered image into which the chart has been drawn.

Usage

From source file:com.church.tools.ChartTools.java

/**
 * Generate line chart.//from  w  ww .  j  a  va  2 s .c  o m
 * 
 * @param title the title
 * @param values the values
 * @param captions the captions
 * @param width the width
 * @param height the height
 * @param color the color
 * 
 * @return the buffered image
 */
public static BufferedImage GenerateLineChart(String title, double[] values, String[] captions, int width,
        int height, Color color) {
    BufferedImage bufferedImage = null;
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (int i = 0; i < values.length; i++) {
        dataset.addValue(values[i], "Balance Timeline", String.valueOf(i + 1));
    }
    JFreeChart chart = ChartFactory.createLineChart(title, "Balance Timeline", "Amount", dataset,
            PlotOrientation.VERTICAL, false, false, false);
    chart.setBackgroundPaint(color);
    bufferedImage = chart.createBufferedImage(width, height);
    return bufferedImage;
}

From source file:utilities.itext.Turnover.java

private static Image createPieChart(HashMap<String, BigDecimal> map, String title) throws Exception {
    DefaultPieDataset data = new DefaultPieDataset();

    for (String key : map.keySet()) {
        data.setValue(key, map.get(key).doubleValue());
    }/*from w w  w .  j  a v a  2 s . c o m*/

    JFreeChart pieChart = ChartFactory.createPieChart(title, data, true, false, Locale.GERMAN);
    //        PiePlot plot = (PiePlot) pieChart.getPlot();
    //        plot.setLabelGenerator(null);

    BufferedImage pie = pieChart.createBufferedImage(500, 500);
    File tempPie = File.createTempFile("png", null);
    ImageIO.write(pie, "png", tempPie);
    Image img = Image.getInstance(tempPie.getPath());

    return img;
}

From source file:pt.ist.expenditureTrackingSystem.presentationTier.actions.statistics.ChartGenerator.java

protected static byte[] createBarChartImage(final CategoryDataset categoryDataset, final String title)
        throws RuntimeException, IOException {
    final JFreeChart chart = createBarChart(categoryDataset, title);
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final BufferedImage bufferedImage = chart.createBufferedImage(625, 475);
    ImageIO.write(bufferedImage, "png", outputStream);
    bufferedImage.flush();/* w w w. j ava2s .c o  m*/
    outputStream.close();
    return outputStream.toByteArray();
}

From source file:com.glaf.chart.util.ChartUtils.java

public static byte[] createChart(Chart chartModel, JFreeChart chart) {
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    try {//from w  ww  . j av a2  s  .c o  m
        baos = new ByteArrayOutputStream();
        bos = new BufferedOutputStream(baos);
        java.awt.image.BufferedImage bi = chart.createBufferedImage(chartModel.getChartWidth(),
                chartModel.getChartHeight());

        if ("png".equalsIgnoreCase(chartModel.getImageType())) {
            EncoderUtil.writeBufferedImage(bi, chartModel.getImageType(), bos);
            ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            ServletUtilities.saveChartAsPNG(chart, chartModel.getChartWidth(), chartModel.getChartHeight(),
                    info, null);
        } else if ("jpeg".equalsIgnoreCase(chartModel.getImageType())) {
            EncoderUtil.writeBufferedImage(bi, chartModel.getImageType(), bos);
            ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            ServletUtilities.saveChartAsJPEG(chart, chartModel.getChartWidth(), chartModel.getChartHeight(),
                    info, null);
        }

        bos.flush();
        baos.flush();

        return baos.toByteArray();

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeQuietly(baos);
        IOUtils.closeQuietly(bos);
    }
}

From source file:pt.ist.expenditureTrackingSystem.presentationTier.actions.statistics.ChartGenerator.java

protected static byte[] createBarChartImage(final ChartData chartData) throws RuntimeException, IOException {
    final JFreeChart chart = createBarChart(chartData.getDataset(), chartData.getTitle());
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final BufferedImage bufferedImage = chart.createBufferedImage(625, 475);
    ImageIO.write(bufferedImage, "png", outputStream);
    bufferedImage.flush();//ww  w. j a  va2  s . co  m
    outputStream.close();
    return outputStream.toByteArray();
}

From source file:problematica.Graficos.java

/**
 * //from ww  w  . jav  a 2  s  .com
 * @param cantCigarros
 */

public static void createGrafico(ArrayList<ArrayList<String>> datos, String nombreArchivo) {

    XYSeries series = new XYSeries("Linea de consumo");
    //como su nombre lo indica el primer valor sera asignado al eje X
    //y el segundo al eje Y

    series.add(0, 0);

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

        series.add((i + 1), Integer.parseInt(datos.get(i).get(0)));

    }

    //se crea un objeto XYDataset requerido mas adelante por el metodo que grafica
    XYDataset juegoDatos = new XYSeriesCollection(series);

    /*aqui se hace la instancia de la nueva grafica invocando al metodo de ChartFactory
    que nos dibujara una grafica de lineas este metodo como casi todos los demas
    recibe los siguientes argumentos:
            
    tipo              valor
    String            nombre de la grafica , aparecera en la parte superior centro
    String            tutulo del eje X
    String            titulo del eje Y
    XYDataset         el conjunto de datos X y Y del tipo XYDataset (aqui cambian el parametro
                      dependiendo del tipo de grafica que se quiere pueden ver todos los parametros
                      en la documentacion aqui <a href="http://www.jfree.org/jfreechart/api/javadoc/index.html
    " title="http://www.jfree.org/jfreechart/api/javadoc/index.html
    ">http://www.jfree.org/jfreechart/api/javadoc/index.html
    </a>                              iremos notando los cambios mas adelante..
     PlotOrientation  la orientacion del grafico puede ser PlotOrientation.VERTICAL o PlotOrientation.HORIZONTAL
     boolean                  muestra u oculta leyendas     
     boolean                  muestra u oculta tooltips
     boolean                  muestra u oculta urls (esta opcion aun no la entiendo del todo)
            
    generalmente solo necesitaremos cambiar los primeros 3 parametros lo demas puede quedarse asi
            
    */
    JFreeChart chart = ChartFactory.createXYLineChart("Grafico de consumo", "dias", "cantidad cigarrillos",
            juegoDatos, PlotOrientation.VERTICAL, true, false, true // Show legend
    );
    //donde guardaremos la imagen?? pues en un bufer jeje
    BufferedImage image = chart.createBufferedImage(500, 500);

    try {
        ImageIO.write(image, "jpg", new File("c:/users/public/nms/grafico/" + nombreArchivo + ".jpg"));
    } catch (IOException e) {
        System.out.println("Error de escritura");
    }

}

From source file:erpsystem.chart.Charts.java

/** Grfico criado para mostrar o histrico de
 * faturamento periodicamente considerando o valor bruto
 * em R$ de lucro./*from w  w w  .  j  a va  2s.  co m*/
*/

public static BufferedImage create002(int w, int h, Calendar initialCalendar, int interval) {
    //Inicio
    DefaultCategoryDataset ds = new DefaultCategoryDataset();
    String LUCRO = "Lucro R$";

    //Configurando os Calendars.
    Calendar finalCalendar = getCurrentCalendar();
    Calendar finalValue = copyCalendar(initialCalendar);
    Calendar initialValue = copyCalendar(initialCalendar);

    while (finalCalendar.after(finalValue)) {

        //ajustando os Calendars ponteiros.
        initialValue = copyCalendar(finalValue);
        finalValue.add(Calendar.DAY_OF_MONTH, interval);

        //toString para depurao.
        String s1 = toString(initialValue);
        String s2 = toString(finalValue);

        //Obtendo as datas como raw para 
        //possibilitar comparao com o banco de dados.
        long value1 = initialValue.getTimeInMillis();
        long value2 = finalValue.getTimeInMillis();

        //Obtendo a nova abstrao de lucro com os intervalos especificados.
        double lucro = Chart001.getValorLucroEm(value1, value2);
        double venda = Chart001.getValorVendaEm(value1, value2);
        double compra = Chart001.getValorCompraEm(value1, value2);

        //Adicionando a nova abstrao na coleo de dados do grfico.
        int y = initialValue.get(Calendar.YEAR);
        int m = initialValue.get(Calendar.MONTH) + 1;
        int d = initialValue.get(Calendar.DAY_OF_MONTH);
        String identifier = d + "/" + m + "/" + y;
        ds.addValue(lucro, "Lucro", identifier);
        ds.addValue(venda, "Venda", identifier);
        ds.addValue(compra, "Compra", identifier);

    }

    //Criando o grfico abstrato em 3D.
    JFreeChart chart = ChartFactory.createBarChart3D("Faturamento", "Faturamento", "Valor R$", ds,
            PlotOrientation.VERTICAL, true, true, false);

    //Criando e retornando a imagem como 
    //mapa de pixels do grfico.
    return chart.createBufferedImage(w, h);
}

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 w w .  j a v a2 s .co m
 *
 * @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:cz.zcu.kiv.eegdatabase.wui.components.utils.ChartUtils.java

public static BufferedImage gererateChartForTopDownloadHistory(ChoiceHistory choiceHistory,
        boolean generateEmptyGraph, List<DownloadStatistic> topDownloadedFilesList, long countOfFilesHistory) {

    long countFile = 0;

    DefaultPieDataset dataset = new DefaultPieDataset();
    if (!generateEmptyGraph && topDownloadedFilesList != null) {
        for (int i = 0; i < topDownloadedFilesList.size(); i++) {
            dataset.setValue(topDownloadedFilesList.get(i).getFileName(),
                    new Long(topDownloadedFilesList.get(i).getCount()));
            countFile = countFile + topDownloadedFilesList.get(i).getCount();
        }//from w ww  .  j a  v a 2s  .  c  om

        if (countOfFilesHistory > countFile) {
            dataset.setValue("Other", countOfFilesHistory - countFile);
        }
    }

    String chartTitle = ResourceUtils.getString("title.dailyStatistic");
    if (choiceHistory == ChoiceHistory.WEEKLY) {
        chartTitle = ResourceUtils.getString("title.weeklyStatistic");

    } else if (choiceHistory == ChoiceHistory.MONTHLY) {
        chartTitle = ResourceUtils.getString("title.monthlyStatistic");
    }

    JFreeChart chart = ChartFactory.createPieChart3D(chartTitle, // 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);
    plot.setNoDataMessage(ResourceUtils.getString("label.noDataMessage"));

    return chart.createBufferedImage(600, 400);
}

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//from  ww w  .j  a va2 s .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);
}