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 plotCoherence(double per[], double[] gamma, String plotString) {

    final String plotTitle = String.format("%04d%03d.%s.%s-%s", date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channelX, channelY);
    final String pngName = String.format("%s/%04d%03d.%s.%s-%s.%s.png", outputDir, date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channelX, channelY, 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("== plotCoherence: request to output plot=[%s] but we are unable to create it "
                + " --> skip plot\n", pngName);
        return;/*  w w w. ja v a2 s . c om*/
    }

    final String legend = String.format("%s--%s", channelX, channelY);
    final XYSeries series1 = new XYSeries(legend);

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

    //final XYItemRenderer renderer1 = new StandardXYItemRenderer();
    final XYLineAndShapeRenderer renderer1 = new XYLineAndShapeRenderer();
    Rectangle rectangle = new Rectangle(3, 3);
    renderer1.setSeriesShape(0, rectangle);
    renderer1.setSeriesShapesVisible(0, true);
    renderer1.setSeriesLinesVisible(0, false);

    Paint[] paints = new Paint[] { Color.red, Color.black };
    renderer1.setSeriesPaint(0, paints[0]);

    final NumberAxis rangeAxis1 = new NumberAxis("Coherence, Gamma");
    rangeAxis1.setRange(new Range(0, 1.2));
    rangeAxis1.setTickUnit(new NumberTickUnit(0.1));

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

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

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

    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:delphsim.model.Resultado.java

/**
 * Mtodo esttico que exporta una grfica <CODE>JFreeChart</CODE> al
 * formato de imagen PNG./*w  w w. ja  va  2s.  co m*/
 * @param destino El fichero de destino.
 * @param chart La grfica a exportar.
 * @param anchura Anchura de la imagen final.
 * @param altura Altura de la imagen final.
 * @throws java.io.IOException Si hubiera algn problema al crear el archivo en disco.
 */
public static void exportarComoPNG(File destino, JFreeChart chart, int anchura, int altura) throws IOException {
    // Para PNG utilizamos las herramientas que ofrece JFreeChart
    ChartUtilities.saveChartAsPNG(destino, chart, anchura, altura);
}

From source file:dk.netarkivet.harvester.harvesting.monitor.StartedJobHistoryChartGen.java

/**
 * Generates a chart in PNG format./*from w w  w. java2  s . c  om*/
 * @param outputFile the output file, it should exist.
 * @param pxWidth the image width in pixels.
 * @param pxHeight the image height in pixels.
 * @param chartTitle the chart title, may be null.
 * @param xAxisTitle the x axis title
 * @param yDataSeriesRange the axis range (null for auto)
 * @param yDataSeriesTitles the Y axis titles.
 * @param timeValuesInSeconds the time values in seconds
 * @param yDataSeries the Y axis value series.
 * @param yDataSeriesColors the Y axis value series drawing colors.
 * @param yDataSeriesTickSuffix TODO explain argument yDataSeriesTickSuffix
 * @param drawBorder draw, or not, the border.
 * @param backgroundColor the chart background color.
 */
final void generatePngChart(File outputFile, int pxWidth, int pxHeight, String chartTitle, String xAxisTitle,
        String[] yDataSeriesTitles, double[] timeValuesInSeconds, double[][] yDataSeriesRange,
        double[][] yDataSeries, Color[] yDataSeriesColors, String[] yDataSeriesTickSuffix, boolean drawBorder,
        Color backgroundColor) {

    // Domain axis
    NumberAxis xAxis = new NumberAxis(xAxisTitle);
    xAxis.setFixedDimension(CHART_AXIS_DIMENSION);
    xAxis.setLabelPaint(Color.black);
    xAxis.setTickLabelPaint(Color.black);

    double maxSeconds = getMaxValue(timeValuesInSeconds);
    TimeAxisResolution xAxisRes = TimeAxisResolution.findTimeUnit(maxSeconds);
    xAxis.setTickUnit(new NumberTickUnit(xAxisRes.tickStep));
    double[] scaledTimeValues = xAxisRes.scale(timeValuesInSeconds);

    String tickSymbol = I18N.getString(locale, "running.job.details.chart.timeunit.symbol." + xAxisRes.name());
    xAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + tickSymbol + "'"));

    // First dataset
    String firstDataSetTitle = yDataSeriesTitles[0];
    XYDataset firstDataSet = createXYDataSet(firstDataSetTitle, scaledTimeValues, yDataSeries[0]);
    Color firstDataSetColor = yDataSeriesColors[0];

    // First range axis
    NumberAxis firstYAxis = new NumberAxis(firstDataSetTitle);

    firstYAxis.setFixedDimension(CHART_AXIS_DIMENSION);
    setAxisRange(firstYAxis, yDataSeriesRange[0]);
    firstYAxis.setLabelPaint(firstDataSetColor);
    firstYAxis.setTickLabelPaint(firstDataSetColor);
    String firstAxisTickSuffix = yDataSeriesTickSuffix[0];
    if (firstAxisTickSuffix != null && !firstAxisTickSuffix.isEmpty()) {
        firstYAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + firstAxisTickSuffix + "'"));
    }

    // Create the plot with domain axis and first range axis
    XYPlot plot = new XYPlot(firstDataSet, xAxis, firstYAxis, null);

    XYLineAndShapeRenderer firstRenderer = new XYLineAndShapeRenderer(true, false);
    plot.setRenderer(firstRenderer);

    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);

    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    firstRenderer.setSeriesPaint(0, firstDataSetColor);

    // Now iterate on next axes
    for (int i = 1; i < yDataSeries.length; i++) {
        // Create axis
        String seriesTitle = yDataSeriesTitles[i];
        Color seriesColor = yDataSeriesColors[i];
        NumberAxis yAxis = new NumberAxis(seriesTitle);

        yAxis.setFixedDimension(CHART_AXIS_DIMENSION);
        setAxisRange(yAxis, yDataSeriesRange[i]);

        yAxis.setLabelPaint(seriesColor);
        yAxis.setTickLabelPaint(seriesColor);

        String yAxisTickSuffix = yDataSeriesTickSuffix[i];
        if (yAxisTickSuffix != null && !yAxisTickSuffix.isEmpty()) {
            yAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + yAxisTickSuffix + "'"));
        }

        // Create dataset and add axis to plot
        plot.setRangeAxis(i, yAxis);
        plot.setRangeAxisLocation(i, AxisLocation.BOTTOM_OR_LEFT);
        plot.setDataset(i, createXYDataSet(seriesTitle, scaledTimeValues, yDataSeries[i]));
        plot.mapDatasetToRangeAxis(i, i);
        XYItemRenderer renderer = new StandardXYItemRenderer();
        renderer.setSeriesPaint(0, seriesColor);
        plot.setRenderer(i, renderer);
    }

    // Create the chart
    JFreeChart chart = new JFreeChart(chartTitle, JFreeChart.DEFAULT_TITLE_FONT, plot, false);

    // Customize rendering
    chart.setBackgroundPaint(Color.white);
    chart.setBorderVisible(true);
    chart.setBorderPaint(Color.BLACK);

    // Render image
    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, pxWidth, pxHeight);
    } catch (IOException e) {
        LOG.error("Chart export failed", e);
    }
}

From source file:org.matsim.contrib.parking.parkingchoice.lib.GeneralLib.java

public static void generateHistogram(String fileName, double[] value, int numberOfBins, String title,
        String xLabel, String yLabel) {
    HistogramDataset dataset = new HistogramDataset();
    dataset.setType(HistogramType.FREQUENCY);
    dataset.addSeries(title, value, numberOfBins);
    String plotTitle = title;//from w  w  w  .j  a  va2 s.  c o m
    String xaxis = xLabel;
    String yaxis = yLabel;
    PlotOrientation orientation = PlotOrientation.VERTICAL;
    boolean show = false;
    boolean toolTips = false;
    boolean urls = false;
    JFreeChart chart = ChartFactory.createHistogram(plotTitle, xaxis, yaxis, dataset, orientation, show,
            toolTips, urls);
    int width = 500;
    int height = 300;
    try {
        ChartUtilities.saveChartAsPNG(new File(fileName), chart, width, height);
    } catch (IOException e) {

    }
}

From source file:jsprit.analysis.toolbox.Plotter.java

private void save(JFreeChart chart, String pngFile) {
    try {// w  w w . j  a v  a 2s  .  c o  m
        ChartUtilities.saveChartAsPNG(new File(pngFile), chart, 1000, 600);
    } catch (IOException e) {
        log.error("cannot plot");
        log.error(e);
        e.printStackTrace();
    }
}

From source file:com.graphhopper.jsprit.analysis.toolbox.Plotter.java

private void save(JFreeChart chart, String pngFile) {
    try {/*from  w  ww  .  j a va 2  s.c om*/
        ChartUtilities.saveChartAsPNG(new File(pngFile), chart, 1000, 600);
    } catch (IOException e) {
        log.error("cannot plot");
        log.error(e.toString());
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

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

/**
 * Getter for the private field value fullCostValueChart.
 * // w w w  .  jav a 2  s.  c  o m
 * @return the fullCostValueChart field value.
 */
public StreamedContent getFullCostValueChart() {
    if (null == fullCostValueChart) {
        LOGGER.debug("getFullCostValueChart(): intialization.");
        File file = new File("fullCostValueChart");
        try {
            ChartUtilities.saveChartAsPNG(file,
                    LineChartGraphistUtil.getColorizedChartFromChart(
                            selectiveChartManager.createSelectiveChart(getSelectedCostResults(),
                                    getSelectedValueResults(),
                                    LocaleUtil.getResourceBundleStringByName(LocaleUtil.COST_CRITERION_NAME)
                                            + "/"
                                            + LocaleUtil.getResourceBundleStringByName(
                                                    LocaleUtil.VALUE_CRITERION_NAME),
                                    LocaleUtil.getResourceBundleStringByName(LocaleUtil.COST_CRITERION_NAME),
                                    LocaleUtil.getResourceBundleStringByName(LocaleUtil.VALUE_CRITERION_NAME),
                                    getCostResults(), getValueResults()),
                            LineChartGraphistUtil.getMaxAbscissaValue(getSelectedCostResults(),
                                    getCostResults()),
                            getSelectedCostResults(), getSelectedValueResults(), getCostResults(),
                            getValueResults()),
                    ColorUtil.FULL_SCREEN_SIZE.width, ColorUtil.FULL_SCREEN_SIZE.height);
            fullCostValueChart = new DefaultStreamedContent(new FileInputStream(file));
        } catch (IOException e) {
            LOGGER.error("Error during the full cost-value chart recovery.", e);
        }
    }
    return fullCostValueChart;
}

From source file:MSUmpire.LCMSPeakStructure.LCMSPeakMS1.java

public void GenerateMassCalibrationRTMap() throws IOException {
    String pngfile = FilenameUtils.getFullPath(ScanCollectionName) + "/"
            + FilenameUtils.getBaseName(ScanCollectionName) + "_masscaliRT.png";
    XYSeries series = new XYSeries("PSM");
    XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
    LoessInterpolator loessInterpolator = new LoessInterpolator(0.75, //bandwidth,
            2//robustnessIters
    );/*  w w  w  .  j av  a2 s .  c  o m*/

    for (PSM psm : this.IDsummary.PSMList.values()) {
        float ppm = InstrumentParameter.CalcSignedPPM(psm.ObserPrecursorMass, psm.NeutralPepMass);
        series.add(new XYDataItem(psm.RetentionTime, ppm));
    }
    double x[] = new double[IDsummary.PSMList.size()];
    double y[] = new double[x.length];
    double currentmin = 0f;
    for (int i = 0; i < series.getItemCount(); i++) {
        x[i] = (double) series.getX(i);
        if (x[i] <= currentmin) {
            x[i] = currentmin + 0.0001f;
        }
        currentmin = x[i];
        y[i] = (double) series.getY(i);
    }

    Masscalibrationfunction = loessInterpolator.interpolate(x, y);
    XYSeries smoothline = new XYSeries("Loess Regression");

    double xvalue = x[0];

    while (xvalue < x[x.length - 1]) {
        smoothline.add(xvalue, Masscalibrationfunction.value(xvalue));
        xvalue += 0.05d;
    }
    xySeriesCollection.addSeries(smoothline);
    xySeriesCollection.addSeries(series);

    JFreeChart chart = ChartFactory.createScatterPlot("Mass calibration", "RT", "Mass error (ppm)",
            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(1.0f));
    xyPlot.setBackgroundPaint(Color.white);
    ChartUtilities.saveChartAsPNG(new File(pngfile), chart, 1000, 600);
}

From source file:org.matsim.contrib.parking.parkingchoice.lib.GeneralLib.java

public static void generateXYScatterPlot(String fileName, double[] x, double[] y, String title, String xLabel,
        String yLabel) {/*from   www.  j  a  v  a  2s  .co m*/

    if (x.length != y.length) {
        DebugLib.stopSystemAndReportInconsistency("dimensions of arrays do not match");
    }

    final XYSeries series1 = new XYSeries(title);

    for (int i = 0; i < x.length; i++) {
        series1.add(x[i], y[i]);
    }

    final XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series1);

    final JFreeChart chart = ChartFactory.createXYLineChart(title, xLabel, yLabel, dataset,
            PlotOrientation.VERTICAL, true, true, false);

    chart.setBackgroundPaint(Color.white);

    final XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);

    final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer.setSeriesLinesVisible(0, false);
    renderer.setSeriesShapesVisible(1, false);
    plot.setRenderer(renderer);

    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    int width = 500;
    int height = 300;

    try {
        ChartUtilities.saveChartAsPNG(new File(fileName), chart, width, height);
    } catch (IOException e) {

    }
}