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:org.esa.beam.pixex.output.ScatterPlotDecoratingStrategy.java

@Override
public void finish() {
    for (Map.Entry<Long, Map<PixExOp.VariableCombination, JFreeChart>> mapEntry : plotMaps.entrySet()) {
        final Map<PixExOp.VariableCombination, JFreeChart> plots = mapEntry.getValue();
        final Long productId = mapEntry.getKey();
        for (Map.Entry<PixExOp.VariableCombination, JFreeChart> entry : plots.entrySet()) {
            final PixExOp.VariableCombination variableCombination = entry.getKey();
            try {
                File targetFile = new File(parent,
                        String.format("%s_scatter_plot_%s_%s_%s.png", filePrefix,
                                variableCombination.originalVariableName,
                                variableCombination.productVariableName, productNames.get(productId)));
                ChartUtilities.saveChartAsPNG(targetFile, entry.getValue(), 600, 400);
            } catch (IOException e) {
                BeamLogManager.getSystemLogger().warning(e.getMessage());
            }//from w  w  w  . j a  v a2s. c  o m
        }
    }
}

From source file:gavisualizer.LineChart.java

@Override
public void saveAsImage(String path, int width, int height) throws IOException {
    // Save image as PNG
    ChartUtilities.saveChartAsPNG(new File(path), _chart, width, height);
}

From source file:MSUmpire.DIA.RTAlignedPepIonMapping.java

private void GenerateRTMapPNG(XYSeriesCollection xySeriesCollection, XYSeries series, float R2)
        throws IOException {
    new File(Workfolder + "/RT_Mapping/").mkdir();
    String pngfile = Workfolder + "/RT_Mapping/"
            + FilenameUtils.getBaseName(LCMSA.mzXMLFileName).substring(0,
                    Math.min(120, FilenameUtils.getBaseName(LCMSA.mzXMLFileName).length() - 1))
            + "_" + FilenameUtils.getBaseName(LCMSB.mzXMLFileName).substring(0,
                    Math.min(120, FilenameUtils.getBaseName(LCMSB.mzXMLFileName).length() - 1))
            + "_RT.png";

    XYSeries smoothline = new XYSeries("RT fitting curve");
    for (XYZData data : regression.PredictYList) {
        smoothline.add(data.getX(), data.getY());
    }//from w  w  w.jav a2 s.  c o m
    xySeriesCollection.addSeries(smoothline);
    xySeriesCollection.addSeries(series);
    JFreeChart chart = ChartFactory.createScatterPlot("Retention time mapping: R2=" + R2,
            "RT:" + FilenameUtils.getBaseName(LCMSA.mzXMLFileName),
            "RT:" + FilenameUtils.getBaseName(LCMSB.mzXMLFileName), xySeriesCollection,
            PlotOrientation.VERTICAL, true, true, false);
    XYPlot xyPlot = (XYPlot) chart.getPlot();
    xyPlot.setDomainCrosshairVisible(true);
    xyPlot.setRangeCrosshairVisible(true);

    XYItemRenderer renderer = xyPlot.getRenderer();
    renderer.setSeriesPaint(1, Color.blue);
    renderer.setSeriesPaint(0, Color.BLACK);
    renderer.setSeriesShape(1, new Ellipse2D.Double(0, 0, 3, 3));
    renderer.setSeriesStroke(1, new BasicStroke(3.0f));
    renderer.setSeriesStroke(0, new BasicStroke(3.0f));
    xyPlot.setBackgroundPaint(Color.white);
    ChartUtilities.saveChartAsPNG(new File(pngfile), chart, 1000, 600);
}

From source file:guineu.modules.filter.report.intensitiesReport.ReportTask.java

/**
 * Create the chart and save it into a png file.
 * @param dataset// www.j  av a 2  s.com
 * @param lipidName
 */
private void createChart(CategoryDataset dataset, String lipidName) {
    try {
        String fieldY;
        if (this.useArea) {
            fieldY = "Area";
        } else {
            fieldY = "Heights";
        }

        JFreeChart chart = ChartFactory.createLineChart("Intensities", "Samples", fieldY, dataset,
                PlotOrientation.VERTICAL, false, false, false);

        // Chart characteristics
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        final NumberAxis axis = (NumberAxis) plot.getRangeAxis();
        axis.setAutoRangeIncludesZero(false);
        LineAndShapeRenderer categoryRenderer = new LineAndShapeRenderer();
        categoryRenderer.setSeriesLinesVisible(0, false);
        categoryRenderer.setSeriesShapesVisible(0, true);
        plot.setRenderer(categoryRenderer);

        // Save all the charts in the folder choosen by the user
        ChartUtilities.saveChartAsPNG(new File(this.reportFileName + "/" + fieldY + ":" + lipidName + ".png"),
                chart, 1000, 500);
    } catch (IOException ex) {
        Logger.getLogger(ReportTask.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:net.nosleep.superanalyzer.analysis.views.MostPlayedDGView.java

public void saveImage(File file, Dimension d) throws IOException {
    if (d == null)
        d = new Dimension(_decadeChartPanel.getWidth(), _decadeChartPanel.getHeight());
    ChartUtilities.saveChartAsPNG(file, _decadeChart, d.width, d.height);
}

From source file:org.miloss.fgsms.services.rs.impl.reports.ws.ThroughputByService.java

/**
 * {@inheritDoc}//  w w  w .j  av a2  s  .  c o m
 */
@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;
        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append(
                "<table  class=\"table table-hover\"><tr><th>URL</th><th>Invocations</th><th>Msg/Day</th><th>Msg/Hour</th><th>Msg/Min</th><th>Msg/Sec</th></tr>");
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            long count = 0;
            try {
                cmd = con.prepareStatement("select count(*) from RawData where URI=? and "
                        + "(UTCdatetime > ?) and (UTCdatetime < ?) ;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                try {
                    if (rs.next()) {
                        count = rs.getLong(1);
                    }
                } catch (Exception ex) {
                    log.log(Level.DEBUG, null, ex);
                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            double d = range.getEnd().getTimeInMillis() - range.getStart().getTimeInMillis();
            double day = d / 86400000;
            double hours = d / 3600000;
            double min = d / 60000;
            double sec = d / 1000;

            data.append("<tr><td>").append(url).append("</td><td>");
            data.append(count + "");
            data.append("</td><td>").append(format.format((double) ((double) count / day))).append("</td><td>")
                    .append(format.format((double) ((double) count / hours))).append("</td><td>")
                    .append(format.format((double) ((double) count / min))).append("</td><td>")
                    .append(format.format((double) ((double) count / sec))).append("</td></tr>");
            if (count > 0) {
                set.addValue((double) ((double) count / day), url, url);
            }

        }
        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);
        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(set.getRowCount()));
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }

        data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
        files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:org.gwaspi.gui.qqPlot.java

/**
 * Runs the test.//from w w  w  .j a  v  a 2  s.  c o m
 */
public void run() {

    this.finished = false;

    List<XYSeries> seriesArray = new ArrayList<XYSeries>();

    Random generator = new Random();
    int seriesNb = -1;
    XYSeriesCollection dataSeries = new XYSeriesCollection();
    XYSeries seriesData = new XYSeries("X");
    XYSeries seriesUpper = new XYSeries("Upper bound");
    XYSeries seriesLower = new XYSeries("Lower bound");

    int N = 10000;
    List<Double> rndChiSqrDist1 = org.gwaspi.statistics.Chisquare.getChiSquareDistributionDf1(N, 1.0f);
    Collections.sort(rndChiSqrDist1);
    List<Double> rndChiSqrDist2 = org.gwaspi.statistics.Chisquare.getChiSquareDistributionDf1(N, 1.0f);
    Collections.sort(rndChiSqrDist2);
    for (int i = 0; i < rndChiSqrDist1.size(); i++) {
        double obsVal = rndChiSqrDist1.get(i) + (generator.nextDouble() * 0.00001);
        double expVal = rndChiSqrDist2.get(i);

        // constant chi-square boundaries
        //         double upperVal = expVal*1.05;
        //         double lowerVal = expVal*0.95;
        //         double upperVal = expVal+Math.pow(Math.E,(1.96*Math.sqrt(1/expVal)));
        //         double lowerVal = expVal-Math.pow(Math.E,(1.96*Math.sqrt(1/expVal)));
        double upperVal = expVal + 1.96 * Math.sqrt(0.05 * (1 - 0.05 / N));
        double lowerVal = expVal - 1.96 * Math.sqrt(0.05 * (1 - 0.05 / N));

        seriesData.add(obsVal, expVal);
        seriesLower.add(expVal, lowerVal);
        seriesUpper.add(expVal, upperVal);
    }

    dataSeries.addSeries(seriesData);
    dataSeries.addSeries(seriesLower);
    dataSeries.addSeries(seriesUpper);
    final XYDataset data = dataSeries;

    // create a scatter chart...
    final boolean withLegend = true;
    JFreeChart chart = ChartFactory.createScatterPlot("QQ-plot", "Obs X", "Exp X", data,
            PlotOrientation.VERTICAL, withLegend, false, false);

    final XYPlot plot = chart.getXYPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(false, true);
    renderer.setSeriesPaint(0, Color.blue);
    renderer.setSeriesPaint(1, Color.gray);
    renderer.setSeriesPaint(2, Color.gray);

    renderer.setBaseShapesVisible(true);
    renderer.setBaseShapesFilled(true);
    renderer.setSeriesShape(0, new Rectangle2D.Double(-1.0, -1.0, 2.0, 2.0));
    renderer.setSeriesShape(1, new Rectangle2D.Double(-2.0, 0.0, 4.0, 0.0));
    renderer.setSeriesShape(2, new Rectangle2D.Double(-2.0, 0.0, 4.0, 0.0));

    plot.setRenderer(renderer);

    try {
        ChartUtilities.saveChartAsPNG(new File(System.getProperty("user.home") + "/Desktop/QQ_plot.png"), chart,
                400, 400);
    } catch (IOException ex) {
        log.error("Problem occurred creating chart", ex);
    }
}

From source file:org.openmicroscopy.shoola.util.ui.graphutils.ChartObject.java

/**
 * Saves the chart as a <code>JPEG</code> or <code>PNG</code>.
 * /*from   w  w w .j  av a2  s  . co  m*/
 * @param file        The file where to save the chart.
 * @param savingType Indicates either to save as a 
 *                 <code>JPEG</code> or <code>PNG</code>
 */
public void saveAs(File file, int savingType) throws Exception {
    if (file == null)
        throw new IllegalArgumentException("No file specified");
    try {
        switch (savingType) {
        case SAVE_AS_PNG:
            ChartUtilities.saveChartAsPNG(file, chart, WIDTH, HEIGHT);
            break;
        case SAVE_AS_JPEG:
            ChartUtilities.saveChartAsJPEG(file, chart, WIDTH, HEIGHT);
        }
    } catch (Exception e) {
        throw new Exception("Unable to save the file.", e);
    }
}

From source file:net.nosleep.superanalyzer.analysis.views.EncodingKindView.java

public void saveImage(File file, Dimension d) throws IOException {
    if (d == null)
        d = new Dimension(_chartPanel.getWidth(), _chartPanel.getHeight());
    ChartUtilities.saveChartAsPNG(file, _chart, d.width, d.height);
}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.CpuUsageReport.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {
    Connection con = Utility.getPerformanceDBConnection();
    try {/*  w  w  w .  jav  a 2  s .  com*/
        PreparedStatement cmd = null;
        ResultSet rs = null;
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append("<table class=\"table table-hover\"><tr><th>URI</th><th>Average CPU Usage %</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)
                    && !isPolicyTypeOf(urls.get(i), PolicyType.PROCESS)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            data.append("<tr><td>").append(url).append("</td>");
            double average = 0;
            try {
                cmd = con.prepareStatement(
                        "select avg(percentcpu) from rawdatamachineprocess where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();
                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td></tr>");
            TimeSeries ts = new TimeSeries(url, Millisecond.class);
            try {
                //ok now get the raw data....
                cmd = con.prepareStatement(
                        "select percentcpu,utcdatetime from rawdatamachineprocess where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();
                while (rs.next()) {
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(2));
                    Millisecond m = new Millisecond(gcal.getTime());
                    ts.addOrUpdate(m, rs.getDouble(1));

                }
                col.addSeries(ts);

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

        }
        data.append("</table>");

        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Percent",
                col, true, false, false);

        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
            // }
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}