Example usage for org.jfree.chart ChartUtilities saveChartAsJPEG

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

Introduction

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

Prototype

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

Source Link

Document

Saves a chart to a file in JPEG format.

Usage

From source file:org.martus.client.swingui.actions.ActionMenuCharts.java

private boolean printToDisk(JFreeChart chart) throws IOException {
    File destFile = chooseDestinationFile();
    if (destFile == null)
        return false;

    int CHART_WIDTH_IN_PIXELS = 800;
    int CHART_HEIGHT_IN_PIXELS = 600;
    ChartUtilities.saveChartAsJPEG(destFile, chart, CHART_WIDTH_IN_PIXELS, CHART_HEIGHT_IN_PIXELS);
    return true;//from  w w  w  . j a  v a 2s.c o m
}

From source file:techtonic.Exports.java

private void saveExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveExportActionPerformed
    format = (jpg.isSelected()) ? "jpg" : "png";
    JFileChooser jfc = new JFileChooser();
    int returnValue = jfc.showOpenDialog(null);
    if (returnValue == JFileChooser.APPROVE_OPTION) {

        File selectedFile = jfc.getSelectedFile();
        String cv = selectedFile.getName();

        try {/* ww w .j a  v  a  2 s. c  om*/
            eWidth = Integer.parseInt(width.getText().trim());
        } catch (NumberFormatException nfe) {
            width.requestFocus();
            return;
        }
        try {
            eHeight = Integer.parseInt(height.getText().trim());
        } catch (NumberFormatException nfe) {
            width.requestFocus();
            return;
        }
        try {
            ChartUtilities.saveChartAsJPEG(new File(Techtonic.getDefaultDirectory(), cv + "." + format),
                    Techtonic.getFreeChart(), eWidth, eHeight);
            Techtonic.seteHeight(eHeight);
            Techtonic.seteWidth(eWidth);
            Techtonic.setFileName(name);
            Techtonic.setFileFormat(format);
            Techtonic.getStatusBar().setForeground(Color.blue);
            Techtonic.getStatusBar().setText("File Exported");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Problem exporting file");
            Techtonic.getStatusBar().setForeground(Color.red);
            Techtonic.getStatusBar().setText("File not exported");
        }
        this.dispose();

    } else {

    }

}

From source file:com.testmax.framework.BasePage.java

private void saveGraph(CreateGraph graph, String file, String title, String xname, String yname) {
    WmLog.getCoreLogger().info("Saving Graphs for " + title);
    //Add graph for Execution Count
    try {/*www .j a  v a2s .  co  m*/

        ChartUtilities.saveChartAsJPEG(new File(file), graph.getChart(), 700, 500);

        WmLog.getCoreLogger().info("Saved Graphs for " + title);

    } catch (IOException e) {

        WmLog.getCoreLogger()
                .info("Problem Occured while saving the Graphs for " + title + " " + e.getMessage());

    }
}

From source file:mil.tatrc.physiology.utilities.csv.plots.MultiPlotter.java

@Override
public void plot(LogListener listener, SESubstanceManager subMgr) {
    //fill PlotJob with needed data if it doesn't exist
    PlotJob job = (PlotJob) listener;/*from  w  w w .java2  s .  c o m*/
    if (job.dataPath == null || job.dataPath.isEmpty()) {
        job.dataPath = "../verification/Scenarios/" + job.verificationDirectory + "/Current Baseline/";
    }
    if (job.dataFile == null || job.dataFile.isEmpty()) {
        job.dataFile = job.name + "Results.zip";
    }

    //Get data contents for all headers when all data is in one file
    if ((data.isEmpty() || data == null) && job.experimentalData == null) {
        try {
            CSVContents csv = new CSVContents(job.dataPath + job.dataFile);
            csv.abbreviateContents = job.resultsSkipNum;
            for (int i = 0; i < job.headers.size(); i++) {
                List<Double> headerData = new ArrayList<Double>();
                csv.readHeader(csv.unitUnderscoreToSpace(job.headers.get(i)), headerData);
                data.put(job.headers.get(i), headerData);
            }
        } catch (IOException e) {
            Log.error("Could not analyze file " + job.dataPath + job.dataFile);
        }
    }
    //Get data contents when we're also using experimental files
    else if ((data.isEmpty() || data == null) && job.experimentalData != null) {
        CSVContents dataCsv = null;
        CSVContents expCsv = null;

        try {
            dataCsv = new CSVContents(job.dataPath + job.dataFile);
            dataCsv.abbreviateContents = job.resultsSkipNum;
        } catch (IOException e) {
            Log.error("Could not analyze file " + job.dataPath + job.dataFile);
        }
        try {
            expCsv = new CSVContents(job.experimentalData);
            expCsv.abbreviateContents = 0; //we'll use all of the experimental data
        } catch (IOException e) {
            Log.error("Could not analyze file " + job.experimentalData);
        }
        try {
            //Get data from X1 and Y1, which should always be from our normal data file
            for (int i = 0; i < job.Y1headers.size(); i++) {
                List<Double> headerData = new ArrayList<Double>();
                dataCsv.readHeader(dataCsv.unitUnderscoreToSpace(job.Y1headers.get(i)), headerData);
                data.put(job.Y1headers.get(i), headerData);
            }
            List<Double> headerData = new ArrayList<Double>();
            dataCsv.readHeader(dataCsv.unitUnderscoreToSpace(job.X1header), headerData);
            data.put(job.X1header, headerData);

            for (int i = 0; i < job.Y2headers.size(); i++) {
                List<Double> headerData2 = new ArrayList<Double>();
                expCsv.readHeader(expCsv.unitUnderscoreToSpace(job.Y2headers.get(i)), headerData2);
                expData.put(job.Y2headers.get(i), headerData2);
            }
            List<Double> headerData2 = new ArrayList<Double>();
            expCsv.readHeader(expCsv.unitUnderscoreToSpace(job.X2header), headerData2);
            expData.put(job.X2header, headerData2);
        } catch (Exception e) {
            Log.error("A problem was encountered reading headers from files.");
        }
    }

    //Catch some errors
    if (job.Y2headers.size() > 0 && job.X2header == null) {
        Log.error("No X2 header specified for job " + job.name
                + ". Each Y axis must have a corresponding X axis.");
        return;
    }

    //Make a dataSeries for desired headers and add to collection(s)
    CSVPlotTool plotTool = new CSVPlotTool(); //to leverage existing functions
    String title = job.name + "_";
    XYSeriesCollection dataSet1 = new XYSeriesCollection();
    XYSeriesCollection dataSet2 = new XYSeriesCollection();
    double maxY1 = 0;
    double minY1 = Double.MAX_VALUE;
    double maxY2 = 0;
    double minY2 = Double.MAX_VALUE;
    for (int i = 0; i < job.Y1headers.size(); i++) {
        XYSeries dataSeries;
        if (job.experimentalData != null)
            dataSeries = plotTool.createXYSeries("BioGears " + job.Y1headers.get(i), data.get(job.X1header),
                    data.get(job.Y1headers.get(i)));
        else
            dataSeries = plotTool.createXYSeries(job.Y1headers.get(i), data.get(job.X1header),
                    data.get(job.Y1headers.get(i)));
        dataSet1.addSeries(dataSeries);
        title = title + job.Y1headers.get(i) + "_";
        maxY1 = maxY1 < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY1;
        minY1 = minY1 > dataSeries.getMinY() ? dataSeries.getMinY() : minY1;
    }
    for (int i = 0; i < job.Y2headers.size(); i++) {
        XYSeries dataSeries;
        if (job.experimentalData != null)
            dataSeries = plotTool.createXYSeries("Experimental " + job.Y2headers.get(i),
                    expData.get(job.X2header), expData.get(job.Y2headers.get(i)));
        else
            dataSeries = plotTool.createXYSeries(job.Y2headers.get(i), data.get(job.X2header),
                    data.get(job.Y2headers.get(i)));
        dataSet2.addSeries(dataSeries);
        title = title + job.Y2headers.get(i) + "_";
        maxY2 = maxY2 < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY2;
        minY2 = minY2 > dataSeries.getMinY() ? dataSeries.getMinY() : minY2;
    }
    title = title + "vs_" + job.X1header;
    if (job.X2header != null && !job.X1header.equalsIgnoreCase(job.X2header))
        title = title + "_" + job.X2header;

    //Override the constructed title if desired
    if (job.titleOverride != null && !job.titleOverride.isEmpty()
            && !job.titleOverride.equalsIgnoreCase("None"))
        title = job.titleOverride;

    //set labels
    String XAxisLabel = job.X1header;
    String YAxisLabel = job.Y1headers.get(0);

    JFreeChart chart = ChartFactory.createXYLineChart(
            job.titleOverride != null && job.titleOverride.equalsIgnoreCase("None") ? "" : title, // chart title
            XAxisLabel, // x axis label
            YAxisLabel, // y axis label
            dataSet1, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    Log.info("Creating Graph " + title);
    XYPlot plot = (XYPlot) chart.getPlot();

    if (!job.logAxis) {
        // Determine Y1 range
        double resMax0 = maxY1;
        double resMin0 = minY1;
        if (Double.isNaN(resMax0) || Double.isNaN(resMin0))
            plot.getDomainAxis(0).setLabel("Range is NaN");
        if (DoubleUtils.isZero(resMin0))
            resMin0 = -0.001;
        if (DoubleUtils.isZero(resMax0))
            resMax0 = 0.001;
        double rangeLength = resMax0 - resMin0;
        ValueAxis yAxis = plot.getRangeAxis(0);
        if (rangeLength != 0)
            yAxis.setRange(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength);//15% buffer so we can see top and bottom clearly  

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null)
                yAxis.setLowerBound(job.Y1LowerBound);
            if (job.Y1UpperBound != null)
                yAxis.setUpperBound(job.Y1UpperBound);
        } catch (Exception e) {
            Log.error(
                    "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
        }

        plot.setRangeAxis(0, yAxis);

        //Add the second Y axis to the right side
        if (!job.Y2headers.isEmpty()) {
            ValueAxis rightYAxis = new NumberAxis();
            // Determine Y2 range
            double resMax1 = maxY2;
            double resMin1 = minY2;
            if (Double.isNaN(resMax1) || Double.isNaN(resMin1))
                plot.getDomainAxis(1).setLabel("Range is NaN");
            if (DoubleUtils.isZero(resMin1))
                resMin1 = -0.001;
            if (DoubleUtils.isZero(resMax1))
                resMax1 = 0.001;
            rangeLength = resMax1 - resMin1;
            if (rangeLength != 0)
                rightYAxis.setRange(resMin1 - 0.15 * rangeLength, resMax1 + 0.15 * rangeLength);
            rightYAxis.setLabel(job.Y2headers.get(0));

            //Override the bounds if desired
            try {
                if (job.Y2LowerBound != null)
                    rightYAxis.setLowerBound(job.Y2LowerBound);
                if (job.Y2UpperBound != null)
                    rightYAxis.setUpperBound(job.Y2UpperBound);
            } catch (Exception e) {
                Log.error(
                        "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
            }

            plot.setRangeAxis(1, rightYAxis);
        }
    } else {
        double resMin = minY1 < minY2 ? minY1 : minY2;
        if (resMin <= 0.0)
            resMin = .00001;
        LogarithmicAxis yAxis = new LogarithmicAxis("Log(" + YAxisLabel + ")");
        yAxis.setLowerBound(resMin);

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null)
                yAxis.setLowerBound(job.Y1LowerBound);
            if (job.Y1UpperBound != null)
                yAxis.setUpperBound(job.Y1UpperBound);
        } catch (Exception e) {
            Log.error(
                    "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
        }

        plot.setRangeAxis(0, yAxis);

        if (!job.Y2headers.isEmpty()) {
            LogarithmicAxis rightYAxis = new LogarithmicAxis("Log(" + job.Y2headers.get(0) + ")");
            rightYAxis.setLowerBound(resMin);

            //Override the bounds if desired
            try {
                if (job.Y2LowerBound != null)
                    rightYAxis.setLowerBound(job.Y2LowerBound);
                if (job.Y2UpperBound != null)
                    rightYAxis.setUpperBound(job.Y2UpperBound);
            } catch (Exception e) {
                Log.error(
                        "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
            }

            plot.setRangeAxis(1, rightYAxis);
        }
    }

    //Override X bounds if desired
    try {
        if (job.X1LowerBound != null)
            plot.getDomainAxis(0).setLowerBound(job.X1LowerBound);
        if (job.X1UpperBound != null)
            plot.getDomainAxis(0).setUpperBound(job.X1UpperBound);
        if (job.X2LowerBound != null)
            plot.getDomainAxis(1).setLowerBound(job.X2LowerBound);
        if (job.X2UpperBound != null)
            plot.getDomainAxis(1).setUpperBound(job.X2UpperBound);
    } catch (Exception e) {
        Log.error("Couldn't set X bounds. You probably tried to set a bound on an axis that doesn't exist.");
    }

    //Add the second dataset if necessary
    if (!job.Y2headers.isEmpty()) {
        plot.setDataset(1, dataSet2);
        plot.mapDatasetToRangeAxis(1, 1);
    }

    //Override labels if desired
    if (job.X1Label != null && !plot.getDomainAxis(0).getLabel().contains("NaN"))
        plot.getDomainAxis(0).setLabel(job.X1Label.equalsIgnoreCase("None") ? "" : job.X1Label);
    if (job.X2Label != null && plot.getDomainAxis(1) != null)
        plot.getDomainAxis(1).setLabel(job.X2Label.equalsIgnoreCase("None") ? "" : job.X2Label);
    if (job.Y1Label != null)
        plot.getRangeAxis(0).setLabel(job.Y1Label.equalsIgnoreCase("None") ? "" : job.Y1Label);
    if (job.Y2Label != null && plot.getRangeAxis(1) != null)
        plot.getRangeAxis(1).setLabel(job.Y2Label.equalsIgnoreCase("None") ? "" : job.Y2Label);

    //Format lines and colors
    plot.setDomainGridlinesVisible(job.showGridLines);
    plot.setRangeGridlinesVisible(job.showGridLines);
    formatMultiPlot(job, chart, dataSet1, dataSet2);

    //Handle legends
    if (job.removeAllLegends)
        chart.removeLegend();

    //Make the file
    try {
        FileUtils.createDirectory(job.outputDir);
        String filename = job.outputFilename == null
                ? job.outputDir + "/" + plotTool.MakeFileName(title) + ".jpg"
                : job.outputDir + "/" + job.outputFilename;
        if (!filename.endsWith(".jpg"))
            filename = filename + ".jpg";
        File JPGFile = new File(filename);
        if (job.imageHeight != null && job.imageWidth != null)
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, job.imageWidth, job.imageHeight);
        else
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, 800);
    } catch (IOException e) {
        Log.error(e.getMessage());
    }

}

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

/**
 * Exports the given chart as JPG in the specified size. The
 * export is written to the given path.//ww  w.  j  ava 2  s .c om
 * 
 * @param chart
 *            The chart to export.
 * @param width
 *            The desired width of the JPG.
 * @param height
 *            The desired height of the JPG.
 * @param path
 *            The path to write the JPG to.
 * @see org.jfree.chart.JFreeChart
 */
private static void exportJPG(JFreeChart chart, int width, int height, String path) {

    try {
        ChartUtilities.saveChartAsJPEG(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 w w w  .ja  v a2 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:View.DialogoEstadisticas.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
    try {//from  w  w w .  j  a  v a  2s . com
        ChartUtilities.saveChartAsJPEG(new File("grafico.jpg"), chart, 700, 700);
    } catch (IOException ex) {
        Logger.getLogger(DialogoEstadisticas.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:mil.tatrc.physiology.utilities.csv.plots.ConvexHullPlotter.java

public void plot(LogListener listener, SESubstanceManager subMgr) {
    //fill PlotJob with needed data if it doesn't exist
    PlotJob job = (PlotJob) listener;/*from w  w w.  ja va 2s.  c o  m*/
    if (job.dataPath == null || job.dataPath.isEmpty()) {
        job.dataPath = "../verification/Scenarios/" + job.verificationDirectory + "/Current Baseline/";
    }
    if (job.dataFile == null || job.dataFile.isEmpty()) {
        job.dataFile = job.name + "Results.zip";
    }

    //Get data contents for all headers
    if (data.isEmpty() || data == null) {
        try {
            CSVContents csv = new CSVContents(job.dataPath + job.dataFile);
            csv.abbreviateContents = job.resultsSkipNum;
            for (int i = 0; i < job.headers.size(); i++) {
                List<Double> headerData = new ArrayList<Double>();
                csv.readHeader(csv.unitUnderscoreToSpace(job.headers.get(i)), headerData);
                data.put(job.headers.get(i), headerData);
            }
        } catch (IOException e) {
            Log.error("Could not analyze file " + job.dataPath + job.dataFile);
        }
    }

    //Catch some errors
    if (job.Y2headers.size() > 0 && job.X2header == null) {
        Log.error("No X2 header specified for job " + job.name
                + ". Each Y axis must have a corresponding X axis.");
        return;
    }

    //Make a dataSeries for desired headers and add to collection(s)
    CSVPlotTool plotTool = new CSVPlotTool(); //to leverage existing functions
    String title = job.name + "_";
    XYSeriesCollection dataSet1 = new XYSeriesCollection();
    XYSeriesCollection dataSet2 = new XYSeriesCollection();
    double maxY1 = 0;
    double minY1 = Double.MAX_VALUE;
    double maxY2 = 0;
    double minY2 = Double.MAX_VALUE;
    for (int i = 0; i < job.Y1headers.size(); i++) {
        XYSeries dataSeriesTop;
        XYSeries dataSeriesBottom;
        XYSeries dataSeriesLeft;
        XYSeries dataSeriesRight;

        //For convex hulls, we have to reorder points before inserting into the dataset
        ConvexHullMaker maker = new ConvexHullMaker();
        List<List<Double>> newVals = new ArrayList<List<Double>>();
        List<List<Double>> splitVals = new ArrayList<List<Double>>();
        newVals = maker.make(data.get(job.X1header), data.get(job.Y1headers.get(i)));
        splitVals = splitHull(newVals);
        dataSeriesTop = plotTool.createXYSeries(job.Y1headers.get(i), splitVals.get(0), splitVals.get(1));
        dataSeriesBottom = plotTool.createXYSeries("", splitVals.get(2), splitVals.get(3));
        dataSeriesLeft = plotTool.createXYSeries("", splitVals.get(4), splitVals.get(5));
        dataSeriesRight = plotTool.createXYSeries("", splitVals.get(6), splitVals.get(7));

        dataSeriesBottom.setKey("REMOVE");
        dataSeriesLeft.setKey("REMOVE");
        dataSeriesRight.setKey("REMOVE");

        dataSet1.addSeries(dataSeriesTop);
        dataSet1.addSeries(dataSeriesBottom);
        dataSet1.addSeries(dataSeriesLeft);
        dataSet1.addSeries(dataSeriesRight);

        title = title + job.Y1headers.get(i) + "_";
        maxY1 = maxY1 < dataSeriesTop.getMaxY() ? dataSeriesTop.getMaxY() : maxY1;
        minY1 = minY1 > dataSeriesBottom.getMinY() ? dataSeriesBottom.getMinY() : minY1;
    }
    for (int i = 0; i < job.Y2headers.size(); i++) {
        XYSeries dataSeriesTop;
        XYSeries dataSeriesBottom;
        XYSeries dataSeriesLeft;
        XYSeries dataSeriesRight;

        ConvexHullMaker maker = new ConvexHullMaker();
        List<List<Double>> newVals = new ArrayList<List<Double>>();
        List<List<Double>> splitVals = new ArrayList<List<Double>>();
        newVals = maker.make(data.get(job.X2header), data.get(job.Y2headers.get(i)));
        splitVals = splitHull(newVals);
        dataSeriesTop = plotTool.createXYSeries(job.Y2headers.get(i), splitVals.get(0), splitVals.get(1));
        dataSeriesBottom = plotTool.createXYSeries("", splitVals.get(2), splitVals.get(3));
        dataSeriesLeft = plotTool.createXYSeries("", splitVals.get(4), splitVals.get(5));
        dataSeriesRight = plotTool.createXYSeries("", splitVals.get(6), splitVals.get(7));

        dataSeriesBottom.setKey("REMOVE");
        dataSeriesLeft.setKey("REMOVE");
        dataSeriesRight.setKey("REMOVE");

        dataSet2.addSeries(dataSeriesTop);
        dataSet2.addSeries(dataSeriesBottom);
        dataSet2.addSeries(dataSeriesLeft);
        dataSet2.addSeries(dataSeriesRight);

        title = title + job.Y2headers.get(i) + "_";
        maxY2 = maxY2 < dataSeriesTop.getMaxY() ? dataSeriesTop.getMaxY() : maxY2;
        minY2 = minY2 > dataSeriesBottom.getMinY() ? dataSeriesBottom.getMinY() : minY2;
    }
    title = title + "vs_" + job.X1header;
    if (job.X2header != null && !job.X1header.equalsIgnoreCase(job.X2header))
        title = title + "_" + job.X2header;

    //Override the constructed title if desired
    if (job.titleOverride != null && !job.titleOverride.isEmpty()
            && !job.titleOverride.equalsIgnoreCase("None"))
        title = job.titleOverride;

    //set labels
    String XAxisLabel = job.X1header;
    String YAxisLabel = job.Y1headers.get(0);

    JFreeChart chart = ChartFactory.createXYLineChart(
            job.titleOverride != null && job.titleOverride.equalsIgnoreCase("None") ? "" : title, // chart title
            XAxisLabel, // x axis label
            YAxisLabel, // y axis label
            dataSet1, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    Log.info("Creating Graph " + title);
    XYPlot plot = (XYPlot) chart.getPlot();

    if (!job.logAxis) {
        // Determine Y1 range
        double resMax0 = maxY1;
        double resMin0 = minY1;
        if (Double.isNaN(resMax0) || Double.isNaN(resMin0))
            plot.getDomainAxis(0).setLabel("Range is NaN");
        if (DoubleUtils.isZero(resMin0))
            resMin0 = -0.001;
        if (DoubleUtils.isZero(resMax0))
            resMax0 = 0.001;
        double rangeLength = resMax0 - resMin0;
        ValueAxis yAxis = plot.getRangeAxis(0);
        yAxis.setRange(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength);//15% buffer so we can see top and bottom clearly  

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null)
                yAxis.setLowerBound(job.Y1LowerBound);
            if (job.Y1UpperBound != null)
                yAxis.setUpperBound(job.Y1UpperBound);
        } catch (Exception e) {
            Log.error(
                    "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
        }

        plot.setRangeAxis(0, yAxis);

        //Add the second Y axis to the right side
        if (!job.Y2headers.isEmpty()) {
            ValueAxis rightYAxis = new NumberAxis();
            // Determine Y2 range
            double resMax1 = maxY2;
            double resMin1 = minY2;
            if (Double.isNaN(resMax1) || Double.isNaN(resMin1))
                plot.getDomainAxis(1).setLabel("Range is NaN");
            if (DoubleUtils.isZero(resMin1))
                resMin1 = -0.001;
            if (DoubleUtils.isZero(resMax1))
                resMax1 = 0.001;
            rangeLength = resMax1 - resMin1;
            rightYAxis.setRange(resMin1 - 0.15 * rangeLength, resMax1 + 0.15 * rangeLength);
            rightYAxis.setLabel(job.Y2headers.get(0));

            //Override the bounds if desired
            try {
                if (job.Y2LowerBound != null)
                    rightYAxis.setLowerBound(job.Y2LowerBound);
                if (job.Y2UpperBound != null)
                    rightYAxis.setUpperBound(job.Y2UpperBound);
            } catch (Exception e) {
                Log.error(
                        "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
            }

            plot.setRangeAxis(1, rightYAxis);
        }
    } else {
        double resMin = minY1 < minY2 ? minY1 : minY2;
        if (resMin <= 0.0)
            resMin = .00001;
        LogarithmicAxis yAxis = new LogarithmicAxis("Log(" + YAxisLabel + ")");
        yAxis.setLowerBound(resMin);

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null)
                yAxis.setLowerBound(job.Y1LowerBound);
            if (job.Y1UpperBound != null)
                yAxis.setUpperBound(job.Y1UpperBound);
        } catch (Exception e) {
            Log.error(
                    "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
        }

        plot.setRangeAxis(0, yAxis);

        if (!job.Y2headers.isEmpty()) {
            LogarithmicAxis rightYAxis = new LogarithmicAxis("Log(" + job.Y2headers.get(0) + ")");
            rightYAxis.setLowerBound(resMin);

            //Override the bounds if desired
            try {
                if (job.Y2LowerBound != null)
                    rightYAxis.setLowerBound(job.Y2LowerBound);
                if (job.Y2UpperBound != null)
                    rightYAxis.setUpperBound(job.Y2UpperBound);
            } catch (Exception e) {
                Log.error(
                        "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
            }

            plot.setRangeAxis(1, rightYAxis);
        }
    }

    //Override X bounds if desired
    try {
        if (job.X1LowerBound != null)
            plot.getDomainAxis(0).setLowerBound(job.X1LowerBound);
        if (job.X1UpperBound != null)
            plot.getDomainAxis(0).setUpperBound(job.X1UpperBound);
        if (job.X2LowerBound != null)
            plot.getDomainAxis(1).setLowerBound(job.X2LowerBound);
        if (job.X2UpperBound != null)
            plot.getDomainAxis(1).setUpperBound(job.X2UpperBound);
    } catch (Exception e) {
        Log.error("Couldn't set X bounds. You probably tried to set a bound on an axis that doesn't exist.");
    }

    //Add the second dataset if necessary
    if (!job.Y2headers.isEmpty()) {
        plot.setDataset(1, dataSet2);
        plot.mapDatasetToRangeAxis(1, 1);
    }

    //Override labels if desired
    if (job.X1Label != null && !plot.getDomainAxis(0).getLabel().contains("NaN"))
        plot.getDomainAxis(0).setLabel(job.X1Label.equalsIgnoreCase("None") ? "" : job.X1Label);
    if (job.X2Label != null && plot.getDomainAxis(1) != null)
        plot.getDomainAxis(1).setLabel(job.X2Label.equalsIgnoreCase("None") ? "" : job.X2Label);
    if (job.Y1Label != null)
        plot.getRangeAxis(0).setLabel(job.Y1Label.equalsIgnoreCase("None") ? "" : job.Y1Label);
    if (job.Y2Label != null && plot.getRangeAxis(1) != null)
        plot.getRangeAxis(1).setLabel(job.Y2Label.equalsIgnoreCase("None") ? "" : job.Y2Label);

    //Format lines and colors
    plotTool.formatXYPlot(chart, job.bgColor);
    plot.setDomainGridlinesVisible(job.showGridLines);
    plot.setRangeGridlinesVisible(job.showGridLines);
    formatConvexHullPlot(job, chart, dataSet1, dataSet2);

    //Handle legends
    if (job.removeAllLegends)
        chart.removeLegend();

    //Make the file
    try {
        FileUtils.createDirectory(job.outputDir);
        String filename = job.outputFilename == null
                ? job.outputDir + "/" + plotTool.MakeFileName(title) + ".jpg"
                : job.outputDir + "/" + job.outputFilename;
        if (!filename.endsWith(".jpg"))
            filename = filename + ".jpg";
        File JPGFile = new File(filename);
        if (job.imageHeight != null && job.imageWidth != null)
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, job.imageWidth, job.imageHeight);
        else
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, 800);
    } catch (IOException e) {
        Log.error(e.getMessage());
    }

}

From source file:edu.illinois.ncsa.datawolf.service.ExecutionsResource.java

public boolean createChartImage(File dataFilePath, File imageFilePath) {
    try {/*  w ww. j  a  v a 2  s.  c o m*/
        JFreeChart chart = createLineGraph(dataFilePath);
        ChartUtilities.saveChartAsJPEG(imageFilePath, chart, 480, 360);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:oscar.form.study.hsfo2.pageUtil.ManageHSFOAction.java

public void generateGraphs(HttpServletRequest request, HttpServletResponse response,
        Map<GraphDesc, TimeSeries> graphDescSeriesMap) {
    if (graphDescSeriesMap == null || graphDescSeriesMap.size() == 0)
        return;/*from ww w.  j  a v  a2 s.  c o m*/

    OscarProperties props = OscarProperties.getInstance();
    String graphDirPath = props.getProperty("hsfo2.generategraph.dir", "/hsfo2Graphs");
    //graphDirPath = this.getServlet().getServletContext().getContextPath() + "/" + graphDirPath;
    //graphDirPath = request.getContextPath() + "/" + graphDirPath; 

    String graphDirRealPath = getServlet().getServletContext().getRealPath(graphDirPath);
    //make sure the directory exists
    File graphDir = new File(graphDirRealPath);
    if (!graphDir.exists() || !graphDir.isDirectory()) {
        graphDir.mkdirs();
    }

    for (Map.Entry<GraphDesc, TimeSeries> entry : graphDescSeriesMap.entrySet()) {
        //one dataset only contain one series here
        GraphDesc graphDesc = entry.getKey();
        TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(entry.getValue());

        JFreeChart chart = ChartFactory.createTimeSeriesChart(graphDesc.getGraphTitle(),
                graphDesc.getXAxisLabel(), graphDesc.getYAxisLabel(), dataset, true, true, true);
        //might need to adjust the XYPlot, see Line 459 of MeasurementGraphAction2
        try {
            String fileName = graphDesc.getFileName() + "." + Calendar.getInstance().getTimeInMillis() + ".jpg";
            String realFilePath = graphDirRealPath + "/" + fileName;
            ChartUtilities.saveChartAsJPEG(new File(realFilePath), chart, 900, 200);
            logger.info("graph file: " + realFilePath + " generated and saved. ");

            request.setAttribute("graphFile." + graphDesc.getFileName(),
                    request.getContextPath() + "/" + graphDirPath + "/" + fileName);
        } catch (IOException e) {
            logger.error("Problem in creating chart: " + e.toString());
        }

    }
}