Example usage for org.jfree.chart ChartUtilities saveChartAsPNG

List of usage examples for org.jfree.chart ChartUtilities saveChartAsPNG

Introduction

In this page you can find the example usage for org.jfree.chart ChartUtilities saveChartAsPNG.

Prototype

public static void saveChartAsPNG(File file, JFreeChart chart, int width, int height) throws IOException 

Source Link

Document

Saves a chart to the specified file in PNG format.

Usage

From source file:com.rcp.wbw.demo.ChartComposite.java

/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.//from   ww  w.jav a 2  s . co  m
 * 
 * @throws IOException
 *             if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(), SWT.SAVE);
    String[] extensions = { "*.png" };
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        // TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart, this.canvas.getSize().x,
                this.canvas.getSize().y);
    }
}

From source file:org.ala.spatial.web.services.GDMWSController.java

public static void generateCharts123(String outputdir) {
    try {/*from  w w  w  . jav a  2  s.  c om*/
        IniReader ir = new IniReader(outputdir + "/gdm_params.txt");
        double intercept = ir.getDoubleValue("GDMODEL", "Intercept");

        // 1. read the ObservedVsPredicted.csv file
        System.out.println("Loading csv data");
        CSVReader csv = new CSVReader(new FileReader(outputdir + "ObservedVsPredicted.csv"));
        List<String[]> rawdata = csv.readAll();
        double[][] dataCht1 = new double[2][rawdata.size() - 1];
        double[][] dataCht2 = new double[2][rawdata.size() - 1];

        // for Chart 1: obs count
        int[] obscount = new int[11];
        for (int i = 0; i < obscount.length; i++) {
            obscount[i] = 0;
        }

        System.out.println("populating data");
        for (int i = 1; i < rawdata.size(); i++) {
            String[] row = rawdata.get(i);
            double obs = Double.parseDouble(row[4]);
            dataCht1[0][i - 1] = Double.parseDouble(row[6]);
            dataCht1[1][i - 1] = obs;

            dataCht2[0][i - 1] = Double.parseDouble(row[5]) - intercept;
            dataCht2[1][i - 1] = obs;

            int obc = (int) Math.round(obs * 10);
            obscount[obc]++;
        }

        DefaultXYDataset dataset1 = new DefaultXYDataset();
        dataset1.addSeries("", dataCht1);

        DefaultXYDataset dataset2 = new DefaultXYDataset();
        dataset2.addSeries("", dataCht2);

        DefaultCategoryDataset dataset3 = new DefaultCategoryDataset();
        for (int i = 0; i < obscount.length; i++) {
            String col = "0." + i + "-0." + (i + 1);
            if (i == 10) {
                col = "0.9-1.0";
            }
            dataset3.addValue(obscount[i] + 100, "col", col);
        }
        generateChartByType("Response Histogram", "Observed Dissimilarity Class", "Number of Site Pairs",
                dataset3, outputdir, "bar", "resphist");

        XYDotRenderer renderer = new XYDotRenderer();
        //Shape cross = ShapeUtilities.createDiagonalCross(3, 1);
        //renderer.setSeriesShape(0, cross);
        renderer.setDotWidth(3);
        renderer.setDotHeight(3);
        renderer.setSeriesPaint(0, Color.BLACK);

        JFreeChart jChart1 = ChartFactory.createScatterPlot(
                "Observed versus predicted compositional dissimilarity",
                "Predicted Compositional Dissimilarity", "Observed Compositional Dissimilarity", dataset1,
                PlotOrientation.VERTICAL, false, false, false);
        jChart1.getTitle().setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));

        XYPlot plot = (XYPlot) jChart1.getPlot();
        plot.setBackgroundPaint(Color.WHITE);
        plot.setDomainZeroBaselineVisible(true);
        plot.setRangeZeroBaselineVisible(true);
        plot.setDomainGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
        plot.setDomainGridlineStroke(new BasicStroke(0.5F, 0, 1));
        plot.setRangeGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
        plot.setRangeGridlineStroke(new BasicStroke(0.5F, 0, 1));
        plot.setRenderer(0, renderer);

        NumberAxis domain = (NumberAxis) plot.getDomainAxis();
        domain.setAutoRangeIncludesZero(false);
        domain.setAxisLineVisible(false);
        domain.setLabelFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

        NumberAxis range = (NumberAxis) plot.getRangeAxis();
        range.setAutoRangeIncludesZero(false);
        range.setAxisLineVisible(false);
        range.setLabelFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

        double dMinPred = domain.getRange().getLowerBound();
        double dMaxPred = domain.getRange().getUpperBound();

        double dMinObs = range.getRange().getLowerBound();
        double dMaxObs = range.getRange().getUpperBound();

        System.out.println("1..pred.min.max: " + dMinPred + ", " + dMaxPred);

        int regressionLineSegs = 10;
        double dInc = (dMaxPred - dMinPred) / regressionLineSegs;
        double[][] dataReg1 = new double[2][regressionLineSegs + 1];
        DefaultXYDataset dsReg1 = new DefaultXYDataset();
        int i = 0;
        for (double d = dMinPred; d <= dMaxPred; d += dInc, i++) {
            dataReg1[0][i] = d;
            dataReg1[1][i] = d;
        }
        dsReg1.addSeries("", dataReg1);
        XYSplineRenderer regressionRenderer = new XYSplineRenderer();
        regressionRenderer.setBaseSeriesVisibleInLegend(true);
        regressionRenderer.setSeriesPaint(0, Color.RED);
        regressionRenderer.setSeriesStroke(0, new BasicStroke(1.5f));
        regressionRenderer.setBaseShapesVisible(false);
        plot.setDataset(1, dsReg1);
        plot.setRenderer(1, regressionRenderer);

        System.out.println("Writing image....");
        ChartUtilities.saveChartAsPNG(new File(outputdir + "plots/obspredissim.png"), jChart1, 600, 400);

        // For chart 3
        JFreeChart jChart2 = ChartFactory.createScatterPlot(
                "Observed compositional dissimilarity vs predicted ecological distance",
                "Predicted ecological distance", "Observed Compositional Dissimilarity", dataset2,
                PlotOrientation.VERTICAL, false, false, false);
        jChart2.getTitle().setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));

        plot = (XYPlot) jChart2.getPlot();
        plot.setBackgroundPaint(Color.WHITE);
        plot.setDomainZeroBaselineVisible(true);
        plot.setRangeZeroBaselineVisible(true);
        plot.setDomainGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
        plot.setDomainGridlineStroke(new BasicStroke(0.5F, 0, 1));
        plot.setRangeGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
        plot.setRangeGridlineStroke(new BasicStroke(0.5F, 0, 1));
        plot.setRenderer(0, renderer);

        domain = (NumberAxis) plot.getDomainAxis();
        domain.setAutoRangeIncludesZero(false);
        domain.setAxisLineVisible(false);
        domain.setLabelFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

        range = (NumberAxis) plot.getRangeAxis();
        range.setAutoRangeIncludesZero(false);
        range.setAxisLineVisible(false);
        range.setLabelFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

        dMinPred = domain.getRange().getLowerBound();
        dMaxPred = domain.getRange().getUpperBound();

        dMinObs = range.getRange().getLowerBound();
        dMaxObs = range.getRange().getUpperBound();

        System.out.println("2.pred.min.max: " + dMinPred + ", " + dMaxPred);

        regressionLineSegs = 10;
        dInc = (dMaxPred - dMinPred) / regressionLineSegs;
        dataReg1 = new double[2][regressionLineSegs + 1];
        dsReg1 = new DefaultXYDataset();
        i = 0;
        for (double d = dMinPred; d <= dMaxPred; d += dInc, i++) {
            dataReg1[0][i] = d;
            dataReg1[1][i] = (1.0 - Math.exp(-d));
        }
        dsReg1.addSeries("", dataReg1);
        regressionRenderer.setBaseSeriesVisibleInLegend(true);
        regressionRenderer.setSeriesPaint(0, Color.RED);
        regressionRenderer.setSeriesStroke(0, new BasicStroke(1.5f));
        regressionRenderer.setBaseShapesVisible(false);
        plot.setDataset(1, dsReg1);
        plot.setRenderer(1, regressionRenderer);

        System.out.println("Writing image....");
        ChartUtilities.saveChartAsPNG(new File(outputdir + "plots/dissimdist.png"), jChart2, 600, 400);

    } catch (Exception e) {
        System.out.println("Unable to generate charts 2 and 3:");
        e.printStackTrace(System.out);
    }
}

From source file:com.munch.exchange.ExchangeChartComposite.java

/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.// ww w . ja  va 2  s. co  m
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {
    FileDialog fileDialog = new FileDialog(this.canvas.getShell(), SWT.SAVE);
    String[] extensions = { "*.png" };
    fileDialog.setFilterExtensions(extensions);
    String filename = fileDialog.open();
    if (filename != null) {
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        //TODO replace getSize by getBounds ?
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart, this.canvas.getSize().x,
                this.canvas.getSize().y);
    }
}

From source file:org.fhaes.jsea.JSEAFrame.java

/**
 * Save the chart to the specified file in PNG format
 * /*from   ww  w  .j  ava  2  s . com*/
 * @param file
 * @throws IOException
 */
private void saveChartPNG(File file) throws IOException {

    log.debug("Saving chart as PNG file");

    ArrayList<BarChartParametersModel> chartlist = jsea.getChartList();
    log.debug("Chart list size " + chartlist.size());
    JFreeChart chart = null;
    if (chartlist.size() == 0) {
        log.debug("No charts in list");
        return;
    } else if (chartlist.size() == 1) {
        chart = chartlist.get(0).getChart();
    } else {
        chart = chartlist.get(segmentComboBox.getSelectedIndex()).getChart();
    }
    if (chart != null) {
        ChartUtilities.saveChartAsPNG(file, chart, 1000, 500);
    } else {
        log.error("Cannot save PNG of chart as chart is null!");
    }
}

From source file:org.moeaframework.analysis.plot.Plot.java

/**
 * Saves the plot to an image file.  The format must be one of {@code png},
 * {@code jpeg}, or {@code svg} (requires JFreeSVG).
 * /*from www . ja v  a 2s.c  o  m*/
 * @param file the file
 * @param format the image format
 * @param width the image width
 * @param height the image height
 * @return a reference to this {@code Plot} instance
 * @throws IOException if an I/O error occurred
 */
public Plot save(File file, String format, int width, int height) throws IOException {
    if (format.equalsIgnoreCase("PNG")) {
        ChartUtilities.saveChartAsPNG(file, chart, width, height);
    } else if (format.equalsIgnoreCase("JPG") || format.equalsIgnoreCase("JPEG")) {
        ChartUtilities.saveChartAsJPEG(file, chart, width, height);
    } else if (format.equalsIgnoreCase("SVG")) {
        String svg = generateSVG(width, height);
        BufferedWriter writer = null;

        try {
            writer = new BufferedWriter(new FileWriter(file));
            writer.write(
                    "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
            writer.write(svg);
            writer.write("\n");
            writer.flush();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    return this;
}

From source file:MSUmpire.DIA.TargetMatchScoring.java

public void MixtureModeling() throws IOException {
    if (libTargetMatches.isEmpty()) {
        return;//w  w w. j  a v  a 2s  .c o  m
    }
    int IDNo = 0;
    int decoyNo = 0;
    int modelNo = 0;
    double IDmean = 0d;
    double Decoymean = 0d;

    for (UmpireSpecLibMatch match : libIDMatches) {
        if (match.BestHit != null) {
            IDNo++;
            IDmean += match.BestHit.UmpireScore;
        }
    }

    decoyNo = decoyModelingList.size();
    for (PeakGroupScore peakGroupScore : decoyModelingList) {
        Decoymean += peakGroupScore.UmpireScore;
    }

    for (UmpireSpecLibMatch match : libTargetMatches) {
        //modelNo+= match.TargetHits.size();
        if (match.BestMS1Hit != null) {
            modelNo++;
        }
        if (match.BestMS2Hit != null) {
            modelNo++;
        }
    }

    Decoymean /= decoyNo;
    IDmean /= IDNo;

    PVector[] points = new PVector[modelNo];
    PVector[] centroids = new PVector[2];

    int idx = 0;
    for (UmpireSpecLibMatch match : libTargetMatches) {
        if (match.BestMS1Hit != null) {
            points[idx] = new PVector(1);
            points[idx].array[0] = match.BestMS1Hit.UmpireScore;
            idx++;
        }
        if (match.BestMS2Hit != null) {
            points[idx] = new PVector(1);
            points[idx].array[0] = match.BestMS2Hit.UmpireScore;
            idx++;
        }
        //            for(PeakGroupScore peakGroupScore : match.TargetHits){
        //                points[idx] = new PVector(1);
        //                points[idx].array[0] = match.BestMS2Hit.UmpireScore;
        //                idx++;
        //            }
    }

    MixtureModel mmc;
    centroids[0] = new PVector(1);
    centroids[0].array[0] = Decoymean;
    centroids[1] = new PVector(1);
    centroids[1].array[0] = IDmean;
    Vector<PVector>[] clusters = KMeans.run(points, 2, centroids);
    MixtureModel mm = ExpectationMaximization1D.initialize(clusters);
    mmc = ExpectationMaximization1D.run(points, mm);
    DecimalFormat df = new DecimalFormat("#.####");
    Logger.getRootLogger()
            .debug("----------------------------------------------------------------------------------------");
    Logger.getRootLogger().debug("No. of modeling points=" + modelNo);
    Logger.getRootLogger().debug("ID hits mean=" + df.format(IDmean));
    Logger.getRootLogger().debug("Decoy hits mean=" + df.format(Decoymean));
    //System.out.print("T-test: p-value=" + df.format(model.ttest.pValue).toString() + "\n");
    Logger.getRootLogger()
            .debug("Incorrect hits model mean=" + df.format(((PVector) mmc.param[0]).array[0]) + " variance="
                    + df.format(((PVector) mmc.param[0]).array[1]) + " weight=" + df.format(mmc.weight[0]));
    Logger.getRootLogger()
            .debug("Correct hits model mean=" + df.format(((PVector) mmc.param[1]).array[0]) + " variance="
                    + df.format(((PVector) mmc.param[1]).array[1]) + " weight=" + df.format(mmc.weight[1]));

    if (((PVector) mmc.param[0]).array[0] > ((PVector) mmc.param[1]).array[0]) {
        return;
    }

    float max = (float) (((PVector) mmc.param[1]).array[0] + 4 * Math.sqrt(((PVector) mmc.param[1]).array[1]));
    float min = (float) (((PVector) mmc.param[0]).array[0] - 4 * Math.sqrt(((PVector) mmc.param[0]).array[1]));

    IDNo = 0;
    decoyNo = 0;
    modelNo = 0;

    for (PeakGroupScore peakGroupScore : decoyModelingList) {
        if (peakGroupScore.UmpireScore > min && peakGroupScore.UmpireScore < max) {
            decoyNo++;
        }
    }

    for (UmpireSpecLibMatch match : libIDMatches) {
        if (match.BestHit != null && match.BestHit.UmpireScore > min && match.BestHit.UmpireScore < max) {
            IDNo++;
        }
    }

    for (UmpireSpecLibMatch match : libTargetMatches) {
        //targetNo += match.TargetHits.size();
        //decoyNo += match.DecoyHits.size();
        if (match.BestMS1Hit != null && match.BestMS1Hit.UmpireScore > min
                && match.BestMS1Hit.UmpireScore < max) {
            modelNo++;
        }
        if (match.BestMS2Hit != null && match.BestMS2Hit.UmpireScore > min
                && match.BestMS2Hit.UmpireScore < max) {
            modelNo++;
        }
        //modelNo += match.TargetHits.size();            
    }

    double[] IDObs = new double[IDNo];
    double[] DecoyObs = new double[decoyNo];
    double[] ModelObs = new double[modelNo];
    idx = 0;
    int didx = 0;
    int midx = 0;
    for (UmpireSpecLibMatch match : libIDMatches) {
        if (match.BestHit != null && match.BestHit.UmpireScore > min && match.BestHit.UmpireScore < max) {
            IDObs[idx++] = match.BestHit.UmpireScore;
        }
    }
    for (PeakGroupScore peakGroupScore : decoyModelingList) {
        if (peakGroupScore.UmpireScore > min && peakGroupScore.UmpireScore < max) {
            DecoyObs[didx++] = peakGroupScore.UmpireScore;
        }
    }

    for (UmpireSpecLibMatch match : libTargetMatches) {
        //            for(PeakGroupScore peak : match.TargetHits){
        //                ModelObs[midx++]=peak.UmpireScore;
        //            }
        if (match.BestMS1Hit != null && match.BestMS1Hit.UmpireScore > min
                && match.BestMS1Hit.UmpireScore < max) {
            ModelObs[midx++] = match.BestMS1Hit.UmpireScore;
        }
        if (match.BestMS2Hit != null && match.BestMS2Hit.UmpireScore > min
                && match.BestMS2Hit.UmpireScore < max) {
            ModelObs[midx++] = match.BestMS2Hit.UmpireScore;
        }
    }

    String pngfile = FilenameUtils.getFullPath(Filename) + "/" + FilenameUtils.getBaseName(Filename) + "_"
            + LibID + "_LibMatchModel.png";
    XYSeries model1 = new XYSeries("Incorrect matches");
    XYSeries model2 = new XYSeries("Correct matches");
    XYSeries model3 = new XYSeries("All target hits");

    String modelfile = FilenameUtils.getFullPath(pngfile) + "/" + FilenameUtils.getBaseName(pngfile)
            + "_ModelPoints.txt";
    FileWriter writer = new FileWriter(modelfile);
    writer.write("UScore\tModel\tCorrect\tDecoy\n");

    int NoPoints = 1000;
    double[] model_kde_x = new double[NoPoints];
    float intv = (max - min) / NoPoints;
    PVector point = new PVector(2);
    for (int i = 0; i < NoPoints; i++) {
        point.array[0] = max - i * intv;
        model_kde_x[i] = point.array[0];
        point.array[1] = mmc.EF.density(point, mmc.param[0]) * mmc.weight[0];
        model1.add(point.array[0], point.array[1]);
        point.array[1] = mmc.EF.density(point, mmc.param[1]) * mmc.weight[1];
        model2.add(point.array[0], point.array[1]);

    }

    KernelDensityEstimator kde = new KernelDensityEstimator();
    kde.SetData(ModelObs);
    double[] model_kde_y = kde.Density(model_kde_x);

    for (int i = 0; i < NoPoints; i++) {
        if (model_kde_x[i] > min && model_kde_x[i] < max) {
            point.array[0] = max - i * intv;
            model_kde_x[i] = point.array[0];
            model3.add(model_kde_x[i], model_kde_y[i]);
            writer.write(point.array[0] + "\t" + mmc.EF.density(point, mmc.param[0]) * mmc.weight[0] + "\t"
                    + mmc.EF.density(point, mmc.param[1]) * mmc.weight[1] + "\t" + model_kde_y[i] + "\n");
        }
    }
    writer.close();
    MixtureModelProb = new float[NoPoints + 1][3];
    float positiveaccu = 0f;
    float negativeaccu = 0f;

    MixtureModelProb[0][0] = (float) model2.getMaxX() + Float.MIN_VALUE;
    MixtureModelProb[0][1] = 1f;
    MixtureModelProb[0][2] = 1f;

    for (int i = 1; i < NoPoints + 1; i++) {
        float positiveNumber = model2.getY(NoPoints - i).floatValue();
        float negativeNumber = model1.getY(NoPoints - i).floatValue();
        MixtureModelProb[i][0] = model2.getX(NoPoints - i).floatValue();
        positiveaccu += positiveNumber;
        negativeaccu += negativeNumber;
        MixtureModelProb[i][2] = positiveNumber / (negativeNumber + positiveNumber);
        MixtureModelProb[i][1] = positiveaccu / (negativeaccu + positiveaccu);
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(model1);
    dataset.addSeries(model2);
    dataset.addSeries(model3);

    HistogramDataset histogramDataset = new HistogramDataset();
    histogramDataset.setType(HistogramType.SCALE_AREA_TO_1);
    histogramDataset.addSeries("ID hits", IDObs, 100);
    histogramDataset.addSeries("Decoy hits", DecoyObs, 100);
    //histogramDataset.addSeries("Model hits", ModelObs, 100);

    JFreeChart chart = ChartFactory.createHistogram(FilenameUtils.getBaseName(pngfile), "Score", "Hits",
            histogramDataset, PlotOrientation.VERTICAL, true, false, false);
    XYPlot plot = chart.getXYPlot();

    NumberAxis domain = (NumberAxis) plot.getDomainAxis();
    domain.setRange(min, max);
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setForegroundAlpha(0.8f);
    chart.setBackgroundPaint(Color.white);

    XYLineAndShapeRenderer render = new XYLineAndShapeRenderer();
    //        render.setSeriesPaint(0, Color.DARK_GRAY);
    //        render.setSeriesPaint(1, Color.DARK_GRAY); 
    //        render.setSeriesPaint(2, Color.GREEN); 
    //        render.setSeriesShape(0, new Ellipse2D.Double(0, 0, 2, 2));
    //        render.setSeriesShape(1, new Ellipse2D.Double(0, 0, 2, 2));
    //        render.setSeriesShape(2, new Ellipse2D.Double(0, 0, 2.5f, 2.5f));
    //        render.setSeriesStroke(1, new BasicStroke(1.0f));
    //        render.setSeriesStroke(0, new BasicStroke(1.0f));
    //        render.setSeriesStroke(2, new BasicStroke(2.0f));
    plot.setDataset(1, dataset);
    plot.setRenderer(1, render);
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    try {
        ChartUtilities.saveChartAsPNG(new File(pngfile), chart, 1000, 600);
    } catch (IOException e) {
    }
}

From source file:org.ala.spatial.web.services.GDMWSController.java

public static void generateChart5(String outputdir, String plotName, String plotData) {
    try {/*from   w  ww  . ja  v  a2s  .  c o m*/

        CSVReader csv = new CSVReader(new FileReader(plotData));
        List<String[]> rawdata = csv.readAll();
        double[][] dataCht = new double[2][rawdata.size() - 1];
        for (int i = 1; i < rawdata.size(); i++) {
            String[] row = rawdata.get(i);
            dataCht[0][i - 1] = Double.parseDouble(row[0]);
            dataCht[1][i - 1] = Double.parseDouble(row[1]);
        }

        DefaultXYDataset dataset = new DefaultXYDataset();
        dataset.addSeries("", dataCht);

        System.out.println("Setting up jChart for " + plotName);
        //generateChartByType(plotName, plotName, "f("+plotName+")", null, outputdir, "xyline", plotName);
        JFreeChart jChart = ChartFactory.createXYLineChart(plotName, plotName, "f(" + plotName + ")", dataset,
                PlotOrientation.VERTICAL, false, false, false);

        jChart.getTitle().setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));

        XYPlot plot = (XYPlot) jChart.getPlot();
        plot.setBackgroundPaint(Color.WHITE);
        plot.setDomainZeroBaselineVisible(true);
        plot.setRangeZeroBaselineVisible(true);
        plot.setDomainGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
        plot.setDomainGridlineStroke(new BasicStroke(0.5F, 0, 1));
        plot.setRangeGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
        plot.setRangeGridlineStroke(new BasicStroke(0.5F, 0, 1));

        NumberAxis domain = (NumberAxis) plot.getDomainAxis();
        domain.setAutoRangeIncludesZero(false);
        domain.setAxisLineVisible(false);
        domain.setLabelFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

        NumberAxis range = (NumberAxis) plot.getRangeAxis();
        range.setAutoRangeIncludesZero(false);
        range.setAxisLineVisible(false);
        range.setLabelFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

        System.out.println("Writing image....");
        ChartUtilities.saveChartAsPNG(new File(outputdir + "plots/" + plotName + ".png"), jChart, 500, 500);
        ChartUtilities.saveChartAsPNG(new File(outputdir + "plots/" + plotName + "_thumb.png"), jChart, 210,
                140);

    } catch (Exception e) {
        System.out.println("Unable to generate charts 2 and 3:");
        e.printStackTrace(System.out);
    }
}

From source file:org.gvsig.remotesensing.scatterplot.chart.ScatterPlotDiagram.java

/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format./* w w w  .j  a  v a  2  s  .  c  o m*/
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {

    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
    ExtensionFileFilter filter = new ExtensionFileFilter(localizationResources.getString("PNG_Image_Files"),
            ".png");
    fileChooser.addChoosableFileFilter(filter);

    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        String filename = fileChooser.getSelectedFile().getPath();
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart, getWidth(), getHeight());
    }

}

From source file:org.ala.spatial.web.services.GDMWSController.java

public static void generateChartByType(String title, String xLabel, String yLabel, Dataset dataset,
        String outputdir, String type, String filename) throws IOException {
    JFreeChart jChart = null;/*from  ww w  .  ja va 2s. c om*/
    if ("line".equalsIgnoreCase(type)) {
        jChart = ChartFactory.createLineChart(title, xLabel, yLabel, (CategoryDataset) dataset,
                PlotOrientation.VERTICAL, false, false, false);
    } else if ("bar".equalsIgnoreCase(type)) {
        System.out.println("Setting up jChart");
        jChart = ChartFactory.createBarChart(title, xLabel, yLabel, (CategoryDataset) dataset,
                PlotOrientation.VERTICAL, false, false, false);
        System.out.println("Writing image....");
    } else if ("xyline".equalsIgnoreCase(type)) {
        jChart = ChartFactory.createXYLineChart(title, xLabel, yLabel, (XYDataset) dataset,
                PlotOrientation.VERTICAL, false, false, false);
    }

    if ("xyline".equalsIgnoreCase(type)) {

        XYPlot plot = (XYPlot) jChart.getPlot();
        plot.setBackgroundPaint(Color.WHITE);
        plot.setRangeZeroBaselineVisible(true);
        plot.setRangeGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
        plot.setRangeGridlineStroke(new BasicStroke(0.5F, 0, 1));

        NumberAxis domain = (NumberAxis) plot.getDomainAxis();
        domain.setAxisLineVisible(false);
        domain.setLabelFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
        domain.setAutoRangeIncludesZero(false);

        NumberAxis range = (NumberAxis) plot.getRangeAxis();
        range.setAutoRangeIncludesZero(false);
        range.setAxisLineVisible(false);
        range.setLabelFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

        //System.out.println("dataset.getColumnCount(): " + dataset.getColumnCount());
        //System.out.println("dataset.getRowCount(): " + dataset.getRowCount());

    } else {

        CategoryPlot plot = (CategoryPlot) jChart.getPlot();
        plot.setBackgroundPaint(Color.WHITE);
        plot.setRangeZeroBaselineVisible(true);
        plot.setRangeGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
        plot.setRangeGridlineStroke(new BasicStroke(0.5F, 0, 1));

        CategoryAxis domain = (CategoryAxis) plot.getDomainAxis();
        domain.setAxisLineVisible(false);
        domain.setLabelFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

        NumberAxis range = (NumberAxis) plot.getRangeAxis();
        range.setAutoRangeIncludesZero(false);
        range.setAxisLineVisible(false);
        range.setLabelFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));

        //System.out.println("dataset.getColumnCount(): " + dataset.getColumnCount());
        //System.out.println("dataset.getRowCount(): " + dataset.getRowCount());

    }

    jChart.getTitle().setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
    ChartUtilities.saveChartAsPNG(new File(outputdir + "plots/" + filename + ".png"), jChart, 900, 500);
}

From source file:pi.bestdeal.gui.InterfacePrincipale.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    int idd = (int) jTable3.getModel().getValueAt(jTable3.getSelectedRow(), 0);
    ChoixStat1 chStat = new ChoixStat1();
    ChoixStat2 chStat2 = new ChoixStat2();

    Object[] options = { "BACK", "NEXT" };
    int a = JOptionPane.showOptionDialog(null, chStat, "", JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.WARNING_MESSAGE, null, options, options[0]);
    int b = 0;//from  w  ww .j a  va  2s  .c om
    if (chStat.jRadiosexe.isSelected() && chStat.jRadioconsult.isSelected()) {
        b = 0;
    }
    if (chStat.jRadiosexe.isSelected() && chStat.jRadiores.isSelected()) {
        b = 1;
    }
    if (chStat.jRadiooperation.isSelected() && chStat.jRadioconsult.isSelected()) {
        b = 2;
    }
    if (chStat.jRadiooperation.isSelected() && chStat.jRadiores.isSelected()) {
        b = 3;
    }
    if (a == 1 && b == 2) {
        chStat.setVisible(false);
        Object[] options2 = { "Annuler", "Afficher la Statistique" };
        int c = JOptionPane.showOptionDialog(null, chStat2, "", JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE, null, options2, options[0]);
        if (c == 1) {
            java.util.Date d1 = chStat2.jDateDebut.getCalendar().getTime();
            java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
            java.util.Date d2 = chStat2.jDatefin.getCalendar().getTime();
            java.sql.Date sqlDate2 = new java.sql.Date(d2.getTime());
            Charts charts = new Charts();

            XYSeriesCollection dataxy = charts.createDataset(sqlDate.toString(), sqlDate2.toString(), idd);
            final JFreeChart chart = ChartFactory.createXYLineChart(
                    "Evolution des Consultation par rapport au temps", "Jours", "Nombre des Consultations", //
                    dataxy, // Dataset
                    PlotOrientation.VERTICAL, // 

                    true, true, false);
            XYItemRenderer rend = chart.getXYPlot().getRenderer();

            ChartPanel crepart = new ChartPanel(chart);
            Plot plot = chart.getPlot();

            JPanel jpan = new JPanel();
            JButton button = new JButton("Sauvegarder");
            button.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        JFileChooser chooser = new JFileChooser();
                        chooser.showSaveDialog(jPanel3);
                        String path = chooser.getSelectedFile().getPath();
                        if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                            path = path + ".png";
                        }
                        File f = new File(path);
                        ChartUtilities.saveChartAsPNG(new File(path), chart, 800, 600);

                        if (f.exists() && !f.isDirectory()) {
                            JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                            Desktop.getDesktop().open(f);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

            jpan.add(crepart);
            jpan.add(button);
            JOptionPane.showConfirmDialog(null, jpan, "Chart d'volution des consultations",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
        }
    }
    if (a == 1 && (b == 3)) {
        Object[] options2 = { "Annuler", "Afficher la Statistique" };
        int c = JOptionPane.showOptionDialog(null, chStat2, "", JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE, null, options2, options[0]);
        if (c == 1) {
            java.util.Date d1 = chStat2.jDateDebut.getCalendar().getTime();
            java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
            java.util.Date d2 = chStat2.jDatefin.getCalendar().getTime();
            java.sql.Date sqlDate2 = new java.sql.Date(d2.getTime());
            Charts charts = new Charts();
            //     JFreeChart chrt = ChartFactory.createXYStepAreaChart(null, null, null, null, PlotOrientation.HORIZONTAL, rootPaneCheckingEnabled, rootPaneCheckingEnabled, rootPaneCheckingEnabled)
            XYSeriesCollection dataxy = charts.createDatasetRes(sqlDate.toString(), sqlDate2.toString(), idd);
            final JFreeChart chart = ChartFactory.createXYLineChart(
                    "Evolution des Consultation par rapport au temps", "Jours", "Nombre des Reservations",
                    dataxy, PlotOrientation.VERTICAL, true, true, false);
            XYItemRenderer rend = chart.getXYPlot().getRenderer();

            ChartPanel crepart = new ChartPanel(chart);
            Plot plot = chart.getPlot();

            JPanel jpan = new JPanel();
            jpan.setLayout(new FlowLayout(FlowLayout.LEADING));
            JButton button = new JButton();

            button.setText("Sauvegarder");
            button.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        JFileChooser chooser = new JFileChooser();
                        chooser.showSaveDialog(jPanel3);
                        String path = chooser.getSelectedFile().getPath();
                        if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                            path = path + ".png";
                        }
                        File f = new File(path);
                        ChartUtilities.saveChartAsPNG(new File(path), chart, 800, 600);

                        if (f.exists() && !f.isDirectory()) {
                            JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                            Desktop.getDesktop().open(f);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

            jpan.add(crepart);
            jpan.add(button);
            JOptionPane.showConfirmDialog(null, jpan, "Test", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.PLAIN_MESSAGE);
        }

    }
    if (a == 1 && b == 0) {
        ConsultationDAO cdao = ConsultationDAO.getInstance();
        DefaultPieDataset union = new DefaultPieDataset();
        union.setValue("Homme", cdao.consultationCounterByGender(false, idd));
        union.setValue("Femme", cdao.consultationCounterByGender(true, idd));

        final JFreeChart repart = ChartFactory.createPieChart3D("Rpartition par Sexe", union, true, true,
                false);
        ChartPanel crepart = new ChartPanel(repart);
        Plot plot = repart.getPlot();
        JPanel jpan = new JPanel();
        JButton button = new JButton("Sauvegarder");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    JFileChooser chooser = new JFileChooser();
                    chooser.showSaveDialog(jPanel3);
                    String path = chooser.getSelectedFile().getPath();
                    if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                        path = path + ".png";
                    }
                    File f = new File(path);
                    ChartUtilities.saveChartAsPNG(new File(path), repart, 800, 600);

                    if (f.exists() && !f.isDirectory()) {
                        JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                        Desktop.getDesktop().open(f);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        jpan.add(crepart);
        jpan.add(button);
        JOptionPane.showConfirmDialog(null, jpan, "", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    }
    if (a == 1 && b == 1) {
        DefaultPieDataset union = new DefaultPieDataset();
        ReservationDAO dAO = ReservationDAO.getInstance();
        union.setValue("Homme", dAO.reservationCounterByGender(false, idd));
        union.setValue("Femme", dAO.reservationCounterByGender(true, idd));

        final JFreeChart repart = ChartFactory.createPieChart3D("Rpartition par Sexe", union, true, true,
                false);
        ChartPanel crepart = new ChartPanel(repart);
        Plot plot = repart.getPlot();
        JPanel jpan = new JPanel();
        JButton button = new JButton("Sauvegarder");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    JFileChooser chooser = new JFileChooser();
                    chooser.showSaveDialog(jPanel3);
                    String path = chooser.getSelectedFile().getPath();
                    if ((!path.contains("jpg")) || (!path.contains("png")) || (!path.contains("jpeg"))) {
                        path = path + ".png";
                    }
                    File f = new File(path);
                    ChartUtilities.saveChartAsPNG(new File(path), repart, 800, 600);

                    if (f.exists() && !f.isDirectory()) {
                        JOptionPane.showMessageDialog(null, "Sauvegarde Effectue");
                        Desktop.getDesktop().open(f);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(InterfacePrincipale.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        jpan.add(crepart);
        jpan.add(button);
        JOptionPane.showConfirmDialog(null, jpan, "Chart de la rpartition des achat par sexe",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    }
}