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:asl.util.PlotMaker.java

public void plotPSD(double per[], double[] model, double[] nhnmPer, double[] nhnm, double[] psd,
        String modelName, String plotString) {

    // plotTitle = "2012074.IU_ANMO.00-BHZ " + plotString
    final String plotTitle = String.format("%04d%03d.%s.%s %s", date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channel, plotString);
    // plot filename = "2012074.IU_ANMO.00-BHZ" + plotString + ".png"
    final String pngName = String.format("%s/%04d%03d.%s.%s.%s.png", outputDir, date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channel, plotString);
    File outputFile = new File(pngName);

    // Check that we will be able to output the file without problems and if not --> return
    if (!checkFileOut(outputFile)) {
        System.out.format(/* w  ww.  j av a 2 s  .co m*/
                "== plotPSD: request to output plot=[%s] but we are unable to create it " + " --> skip plot\n",
                pngName);
        return;
    }

    Boolean plotNHNM = false;
    //if (nhnm.length > 0) {
    if (nhnm != null) {
        plotNHNM = true;
    }

    final XYSeries series1 = new XYSeries(modelName);
    final XYSeries series2 = new XYSeries(channel.toString());
    final XYSeries series3 = new XYSeries("NHNM");

    for (int k = 0; k < per.length; k++) {
        series1.add(per[k], model[k]);
        series2.add(per[k], psd[k]);
    }

    if (plotNHNM) {
        for (int k = 0; k < nhnmPer.length; k++) {
            series3.add(nhnmPer[k], nhnm[k]);
        }
    }

    //final XYItemRenderer renderer = new StandardXYItemRenderer();
    final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    Rectangle rectangle = new Rectangle(3, 3);

    renderer.setSeriesShape(0, rectangle);
    renderer.setSeriesShapesVisible(0, false);
    renderer.setSeriesLinesVisible(0, true);

    renderer.setSeriesShape(1, rectangle);
    renderer.setSeriesShapesVisible(1, true);
    renderer.setSeriesLinesVisible(1, false);

    renderer.setSeriesShape(2, rectangle);
    renderer.setSeriesShapesVisible(2, false);
    renderer.setSeriesLinesVisible(2, true);

    Paint[] paints = new Paint[] { Color.blue, Color.red, Color.black };
    renderer.setSeriesPaint(0, paints[0]);
    renderer.setSeriesPaint(1, paints[1]);
    renderer.setSeriesPaint(2, paints[2]);

    final NumberAxis rangeAxis1 = new NumberAxis("PSD 10log10(m**2/s**4)/Hz dB");
    //rangeAxis1.setRange( new Range(-190, -120));
    rangeAxis1.setRange(new Range(-190, -95));
    rangeAxis1.setTickUnit(new NumberTickUnit(5.0));

    final LogarithmicAxis horizontalAxis = new LogarithmicAxis("Period (sec)");
    horizontalAxis.setRange(new Range(0.05, 10000));

    final XYSeriesCollection seriesCollection = new XYSeriesCollection();
    seriesCollection.addSeries(series1);
    seriesCollection.addSeries(series2);

    if (plotNHNM) {
        seriesCollection.addSeries(series3);
    }

    final XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, horizontalAxis, rangeAxis1, renderer);

    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.black);
    xyplot.setDomainGridlinePaint(Color.black);

    final JFreeChart chart = new JFreeChart(xyplot);
    chart.setTitle(new TextTitle(plotTitle));

    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, 500, 300);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");

    }
}

From source file:org.gwaspi.reports.OutputTest.java

private void writeQQPlotFromAssociationData(String outName, int width, int height) throws IOException {

    // Generating XY scatter plot with loaded data
    XYPlot qqPlot = GenericReportGenerator.buildQQPlot(getParams().getTestOperationKey(), qqPlotDof);

    JFreeChart chart = new JFreeChart("X QQ", JFreeChart.DEFAULT_TITLE_FONT, qqPlot, true);

    OperationMetadata rdOPMetadata = getOperationService()
            .getOperationMetadata(getParams().getTestOperationKey());
    String imagePath = Study.constructReportsPath(rdOPMetadata.getStudyKey()) + outName + ".png";
    try {//w ww.j a  va 2s.com
        ChartUtilities.saveChartAsPNG(new File(imagePath), chart, width, height);
    } catch (IOException ex) {
        throw new IOException("Problem occurred creating chart", ex);
    }
}

From source file:org.matsim.contrib.freight.usecases.analysis.LegHistogram.java

/**
 * Writes a graphic showing the number of departures, arrivals and vehicles
 * en route of all legs/trips with the specified transportation mode to the
 * specified file.//from ww w .ja v a  2  s  . com
 *
 * @param filename
 * @param legMode
 *
 * @see #getGraphic(String)
 */
public void writeGraphic(final String filename, final String legMode) {
    try {
        ChartUtilities.saveChartAsPNG(new File(filename), getGraphic(legMode), 1024, 768);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:JDAC.JDAC.java

public void exportPNG() {
    DateFormat df = new SimpleDateFormat("ddmmyy_HHmm");

    FileDialog fd = new FileDialog(this, "Export as...", FileDialog.SAVE);

    fd.setFile("Chart_" + df.format(new Date()) + ".png");
    fd.setVisible(true);/*w w w. j av  a 2s .com*/

    if (fd.getFile() == null) {
        setStatus("Export PNG canceled");
        //export canceled
        return;
    }

    mChart.setTitle(currentSensor);

    try {
        ChartUtilities.saveChartAsPNG(new File(fd.getDirectory() + fd.getFile()), mChart,
                Definitions.exportPNGwidth, Definitions.exportPNGheight);
        setStatus("Export PNG successful");
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, "" + "Error while exporting chart...\n"
                + "If the error persists please contact the system administrator");
        mChart.setTitle(mainChartPreviewTitle);
        return;
    }

    mChart.setTitle(mainChartPreviewTitle);
}

From source file:com.che.software.testato.web.controller.SelectivePrioritizationController.java

/**
 * Getter for the private field value fitRiskChart.
 * /*ww  w.j  av a  2  s  .c  o m*/
 * @return the fitRiskChart field value.
 */
public StreamedContent getFitRiskChart() {
    if (null == fitRiskChart) {
        LOGGER.debug("getFitRiskChart(): intialization.");
        File file = new File("fitRiskChart");
        try {
            ChartUtilities.saveChartAsPNG(file,
                    LineChartGraphistUtil.getColorizedChartFromChart(
                            selectiveChartManager.createSelectiveChart(getSelectedFitResults(),
                                    getSelectedRiskResults(),
                                    LocaleUtil.getResourceBundleStringByName(LocaleUtil.FIT_CRITERION_NAME)
                                            + "/"
                                            + LocaleUtil.getResourceBundleStringByName(
                                                    LocaleUtil.RISK_CRITERION_NAME),
                                    LocaleUtil.getResourceBundleStringByName(LocaleUtil.FIT_CRITERION_NAME),
                                    LocaleUtil.getResourceBundleStringByName(LocaleUtil.RISK_CRITERION_NAME),
                                    getFitResults(), getRiskResults()),
                            LineChartGraphistUtil.getMaxAbscissaValue(getSelectedFitResults(), getFitResults()),
                            getSelectedFitResults(), getSelectedRiskResults(), getFitResults(),
                            getRiskResults()),
                    ColorUtil.MICRO_SIZE.width, ColorUtil.MICRO_SIZE.height);
            fitRiskChart = new DefaultStreamedContent(new FileInputStream(file));
        } catch (IOException e) {
            LOGGER.error("Error during the fit-risk chart recovery.", e);
        }
    }
    return fitRiskChart;
}

From source file:GenAppStoreSales.java

public static void genPlot(String periodType, String plotFileName, String pursuedPeriodDate,
        ArrayList<String> cLabels, ArrayList<ArrayList<Integer>> cUnits) {
    windowTitle = "TOnOa Music " + periodType + " Sales " + pursuedPeriodDate;
    GenAppStoreSales demo = new GenAppStoreSales(windowTitle, cLabels, cUnits);
    demo.pack();//from ww  w .  j av a  2s .  com
    RefineryUtilities.centerFrameOnScreen(demo);
    //      demo.setVisible(true);

    try {
        File plotFile = new File(chartPath + "/" + plotFileName + ".png");
        ChartUtilities.saveChartAsPNG(plotFile, chart, widthChart, heightChart);
        System.out.println("Generated " + periodType + " chart " + plotFileName);
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 
    }
}

From source file:de.xirp.chart.ChartUtil.java

/**
 * Exports the given chart as PNG in the specified size. The
 * export is written to the given path./*from  w  w  w .  ja v a 2 s. co  m*/
 * 
 * @param chart
 *            The chart to export.
 * @param width
 *            The desired width of the PNG.
 * @param height
 *            The desired height of the PNG.
 * @param path
 *            The path to write the PNG to.
 * @see org.jfree.chart.JFreeChart
 */
private static void exportPNG(JFreeChart chart, int width, int height, String path) {

    try {
        ChartUtilities.saveChartAsPNG(new File(path), chart, width, height);
    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() //$NON-NLS-1$
                + Constants.LINE_SEPARATOR, e);
    }
}

From source file:de.dfki.owlsmx.gui.ResultVisualization.java

private void saveActionPerformed(java.awt.event.ActionEvent event) {//GEN-FIRST:event_saveActionPerformed
    try {/*from  ww w.  j ava  2 s. c o m*/
        if (event.getSource().equals(save)) {
            if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                if (fc.getFileFilter().getClass().equals((new PNGFilter()).getClass()))
                    if (fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".png"))
                        ChartUtilities.saveChartAsPNG(fc.getSelectedFile(), chart, graphPrintWidth,
                                graphPrintHeight);
                    else
                        ChartUtilities.saveChartAsPNG(new File(fc.getSelectedFile().getAbsolutePath() + ".png"),
                                chart, graphPrintWidth, graphPrintHeight);

                else if (fc.getFileFilter().getClass().equals((new JPGFilter()).getClass()))
                    if (fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".png"))
                        ChartUtilities.saveChartAsJPEG(fc.getSelectedFile(), chart, graphPrintWidth,
                                graphPrintHeight);
                    else
                        ChartUtilities.saveChartAsJPEG(
                                new File(fc.getSelectedFile().getAbsolutePath() + ".png"), chart,
                                graphPrintWidth, graphPrintHeight);

                else if (fc.getFileFilter().getClass().equals((new PDFFilter()).getClass()))
                    if (fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".pdf"))
                        Converter.convertToPdf(chart, graphPrintWidth, graphPrintHeight,
                                fc.getSelectedFile().getAbsolutePath());
                    else
                        Converter.convertToPdf(chart, graphPrintWidth, graphPrintHeight,
                                fc.getSelectedFile().getAbsolutePath() + ".pdf");
                else if (fc.getFileFilter().getClass().equals((new EPSFilter()).getClass()))
                    printGraphics2DtoEPS(fc.getSelectedFile().getAbsolutePath());
            }
        }
    } catch (Exception e) {
        GUIState.displayWarning(e.getClass().toString(),
                "Couldn't save file " + fc.getSelectedFile().getAbsolutePath());
        e.printStackTrace();
    }
}

From source file:org.gephi.ui.utils.ChartsUtils.java

private static void writeChart(final StringBuilder sb, final JFreeChart chart, final Dimension dimension,
        final String fileName) throws IOException {
    TempDir tempDir = TempDirUtils.createTempDir();
    String imageFile = "";
    File file = tempDir.createFile(fileName);
    imageFile = "<center><img src=\"file:" + file.getAbsolutePath() + "\"</img></center>";
    ChartUtilities.saveChartAsPNG(file, chart, dimension.width, dimension.height);

    sb.append(imageFile);/*from   w ww.  j a  v a2s . co  m*/
}

From source file:playground.christoph.evacuation.analysis.AgentsInMunicipalityEventsHandler.java

private void writeGraphic(final String filename, JFreeChart chart) {
    try {//from ww w .  j av  a2 s  .c  om
        ChartUtilities.saveChartAsPNG(new File(filename), chart, 1024, 768);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}