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.gephi.datalab.plugin.manipulators.columns.ColumnValuesFrequency.java

private void writePieChart(final StringBuilder sb, JFreeChart chart, Dimension dimension) throws IOException {

    TempDir tempDir = TempDirUtils.createTempDir();
    String imageFile = "";
    String fileName = "frequencies-pie-chart.png";
    File file = tempDir.createFile(fileName);
    imageFile = "<center><img src=\"file:" + file.getAbsolutePath() + "\"</img></center>";
    ChartUtilities.saveChartAsPNG(file, chart, dimension != null ? dimension.width : 1000,
            dimension != null ? dimension.height : 1000);

    sb.append(imageFile);// w w w.  j a v a  2s . c o m
}

From source file:com.uttesh.pdfngreport.handler.PdfReportHandler.java

/**
 * This method will generate the chart image file by using the Jfree chart
 * library//  ww w.  j  a  v a  2 s . c o  m
 *
 * @param dataSet
 * @throws FileNotFoundException
 * @throws IOException
 *
 * @see DefaultPieDataset
 */
public void generateChart(DefaultPieDataset dataSet, String os) throws FileNotFoundException, IOException {
    try {
        JFreeChart chart = ChartFactory.createPieChart3D("", dataSet, true, true, false);
        ChartStyle.theme(chart);
        PiePlot3D plot = (PiePlot3D) chart.getPlot();
        plot.setForegroundAlpha(0.6f);
        plot.setCircular(true);
        plot.setSectionPaint("Passed", Color.decode("#019244"));
        plot.setSectionPaint("Failed", Color.decode("#EE6044"));
        plot.setSectionPaint("Skipped", Color.decode("#F0AD4E"));
        Color transparent = new Color(0.0f, 0.0f, 0.0f, 0.0f);
        plot.setLabelOutlinePaint(transparent);
        plot.setLabelBackgroundPaint(transparent);
        plot.setLabelShadowPaint(transparent);
        plot.setLabelLinkPaint(Color.GRAY);
        Font font = new Font("SansSerif", Font.PLAIN, 10);
        plot.setLabelFont(font);
        PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator("{0}: {1} ({2})",
                new DecimalFormat("0"), new DecimalFormat("0%"));
        plot.setLabelGenerator(gen);
        if (os != null && os.equalsIgnoreCase("w")) {
            ChartUtilities.saveChartAsPNG(
                    new File(reportLocation + Constants.BACKWARD_SLASH + Constants.REPORT_CHART_FILE), chart,
                    560, 200);
        } else {
            ChartUtilities.saveChartAsPNG(
                    new File(reportLocation + Constants.FORWARD_SLASH + Constants.REPORT_CHART_FILE), chart,
                    560, 200);
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
        if (os != null && os.equalsIgnoreCase("w")) {
            new File(reportLocation + Constants.BACKWARD_SLASH + Constants.REPORT_CHART_FILE).delete();
        } else {
            new File(reportLocation + Constants.FORWARD_SLASH + Constants.REPORT_CHART_FILE).delete();
        }
        System.exit(-1);
    }
}

From source file:com.jbombardier.console.charts.XYTimeChartPanel.java

public void complete() {
    String filename = imageFilename;

    if (filename == null) {
        filename = chart.getTitle().getText() + ".png";
    }/*from  ww w .java2  s.c o  m*/

    File file = new File(filename);
    try {
        ChartUtilities.saveChartAsPNG(file, chart, imageFileWidth, imageFileHeight);
        Out.out("Chart written to '{}'", file.getAbsolutePath());
    } catch (IOException e) {
        throw new RuntimeException(String.format("Failed to save png [%s]", file.getAbsolutePath()), e);
    }
}

From source file:playground.wrashid.parkingSearch.ppSim.jdepSim.searchStrategies.analysis.ComparisonGarageCounts.java

public static void logRelativeError(LinkedList<ParkingEventDetails> parkingEventDetails,
        String outputFileName) {//from ww  w .j ava 2 s. c  om
    int startIndex = 28;
    int endIndex = 76;

    Double countsScalingFactor = ZHScenarioGlobal.loadDoubleParam("ComparisonGarageCounts.countsScalingFactor");

    HashMap<Id, ParkingOccupancyBins> parkingOccupancyBins = new HashMap<Id, ParkingOccupancyBins>();

    for (ParkingEventDetails ped : parkingEventDetails) {
        ParkingActivityAttributes parkingActivityAttributes = ped.parkingActivityAttributes;
        Id facilityId = parkingActivityAttributes.getFacilityId();
        if (mappingOfParkingNameToParkingId.values().contains(facilityId.toString())) {
            if (!parkingOccupancyBins.containsKey(facilityId)) {
                parkingOccupancyBins.put(facilityId, new ParkingOccupancyBins());
            }
            ParkingOccupancyBins parkingOccupancyBin = parkingOccupancyBins.get(facilityId);
            parkingOccupancyBin.inrementParkingOccupancy(parkingActivityAttributes.getParkingArrivalTime(),
                    parkingActivityAttributes.getParkingArrivalTime()
                            + parkingActivityAttributes.getParkingDuration());
        }
    }

    HashMap<String, Double[]> occupancyOfAllSelectedParkings = SingleDayGarageParkingsCount
            .getOccupancyOfAllSelectedParkings(countsMatrix);

    List<Double> relativeErrorList = new ArrayList<Double>();

    for (String parkingName : selectedParkings) {
        Double[] occupancyBins = occupancyOfAllSelectedParkings.get(parkingName);
        double measuredOccupancySum = 0;
        for (int i = startIndex; i < endIndex; i++) {
            measuredOccupancySum += countsScalingFactor * occupancyBins[i];
        }

        Id<PParking> parkingId = Id.create(mappingOfParkingNameToParkingId.get(parkingName), PParking.class);
        ParkingOccupancyBins pob = parkingOccupancyBins.get(parkingId);

        double simulatedOccupancySum = 0;

        if (pob != null) {
            for (int i = startIndex; i < endIndex; i++) {
                simulatedOccupancySum += pob.getOccupancy()[i];
            }
        }

        double relativeError = -1;
        if (measuredOccupancySum != 0) {
            relativeError = Math.abs(simulatedOccupancySum - measuredOccupancySum) / measuredOccupancySum;
        }

        //System.out.println(parkingId + ": " +  relativeError);
        relativeErrorCounts.put(parkingId, relativeError);

        relativeErrorList.add(new Double(relativeError));
    }
    boxPlotDataSet.add(relativeErrorList, "relativeError", ZHScenarioGlobal.iteration);

    final NumberAxis yAxis = new NumberAxis("Value");
    yAxis.setAutoRangeIncludesZero(false);
    final BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
    renderer.setFillBox(false);
    final JFreeChart chart = ChartFactory.createBoxAndWhiskerChart("Rel. Error - Garage Parking Counts",
            "Iteration", "rel. Error", boxPlotDataSet, false);

    int width = 500;
    int height = 300;

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

    }

    // print median rel. error:
    Double[] numArray = relativeErrorList.toArray(new Double[0]);
    Arrays.sort(numArray);
    double median;
    if (numArray.length % 2 == 0)
        median = (numArray[numArray.length / 2] + numArray[numArray.length / 2 + 1]) / 2;
    else
        median = numArray[numArray.length / 2];
    log.info("median rel. error:" + median);
}

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

/**
 * {@inheritDoc}/* w ww . j a v a 2 s.  co  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>Consumer</th><th>URL</th><th>Invocations</th></tr>");
        Set<String> consumers = new HashSet<String>();

        //   for (int i = 0; i < (consumers.size()-1); i++) {
        for (int k = 0; k < urls.size(); k++) {
            if (!isPolicyTypeOf(urls.get(k), PolicyType.TRANSACTIONAL)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(k), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(k)));
            consumers.clear();
            try {
                try {
                    cmd = con.prepareStatement(
                            "select consumeridentity from rawdata where uri=? and (UTCdatetime > ?) and (UTCdatetime < ?) group by consumeridentity;");
                    cmd.setString(1, urls.get(k));
                    cmd.setLong(2, range.getStart().getTimeInMillis());
                    cmd.setLong(3, range.getEnd().getTimeInMillis());
                    rs = cmd.executeQuery();
                    while (rs.next()) {
                        String s = rs.getString(1);
                        if (!Utility.stringIsNullOrEmpty(s)) {
                            String ids[] = s.split(";");
                            for (int i = 0; i < ids.length; i++) {
                                if (!Utility.stringIsNullOrEmpty(ids[i])) {

                                    consumers.add(ids[i]);

                                }
                            }
                        }

                    }
                } catch (Exception ex) {
                    log.log(Level.WARN,
                            " error querying database forINVOCATIONS_BY_CONSUMER_BY_SERVICE" + urls.get(k), ex);
                } finally {
                    DBUtils.safeClose(rs);
                    DBUtils.safeClose(cmd);
                }
                consumers.add("unspecified");

                //ok for this service, count the times each consumer as hit it
                Iterator<String> iterator = consumers.iterator();
                while (iterator.hasNext()) {
                    String user = iterator.next();
                    long count = 0;
                    try {
                        cmd = con.prepareStatement("select count(*) from RawData where URI=? and "
                                + "(UTCdatetime > ?) and (UTCdatetime < ?) and consumeridentity ~* ?;");
                        cmd.setString(1, urls.get(k));
                        cmd.setLong(2, range.getStart().getTimeInMillis());
                        cmd.setLong(3, range.getEnd().getTimeInMillis());
                        cmd.setString(4, user);

                        rs = cmd.executeQuery();

                        try {
                            if (rs.next()) {
                                count = rs.getLong(1);
                            }
                        } catch (Exception ex) {
                            log.log(Level.WARN, " error querying database forINVOCATIONS_BY_CONSUMER_BY_SERVICE"
                                    + urls.get(k), ex);
                        }
                    } catch (Exception ex) {
                        log.log(Level.WARN, null, ex);
                    } finally {
                        DBUtils.safeClose(rs);
                        DBUtils.safeClose(cmd);
                    }

                    if (count > 0) { //cut down on the chatter
                        data.append("<tr><td>").append(url).append("</td><td>").append(Utility.encodeHTML(user))
                                .append("</td><td>");
                        data.append(count + "");
                        data.append("</td></tr>");

                        set.addValue(count, user, urls.get(k));

                    }
                }

                //this is for anonymous users or for when an identity was not
                //recorded by the agent
                long count = 0;
                try {
                    cmd = con.prepareStatement("select count(*) from RawData where URI=? and "
                            + "(UTCdatetime > ?) and (UTCdatetime < ?) and consumeridentity is null;");
                    cmd.setString(1, urls.get(k));
                    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.WARN,
                                " error querying database forINVOCATIONS_BY_CONSUMER_BY_SERVICE" + urls.get(k),
                                ex);
                    }
                } catch (Exception ex) {
                    log.log(Level.WARN, null, ex);
                } finally {
                    DBUtils.safeClose(rs);
                    DBUtils.safeClose(cmd);
                }

                if (count > 0) { //cut down on the chatter
                    data.append("<tr><td>").append(url).append("</td><td>(not recorded)</td><td>");
                    data.append(count + "");
                    data.append("</td></tr>");

                    set.addValue(count, "unspecified", url);
                }

            } catch (Exception ex) {
                data.append("0 bytes</td></tr>");
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            }
        }
        //  insert query for unspecified chart = org.jfree.chart.ChartFactory.createBarChart(toFriendlyName(get.getType()), "Service URL", "", set, PlotOrientation.HORIZONTAL, true, false, false);
        data.append("</table>");
        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);
        try {
            int height = pixelHeightCalc(set.getColumnCount());
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, height);
        } 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:asl.util.PlotMaker.java

public void plotZNE_3x3(ArrayList<double[]> channelData, double[] xsecs, int nstart, int nend,
        String eventString, String plotString) {

    // Expecting 9 channels packed like:            Panel   Trace1  Trace2  Trace3
    // channels[0] = 00-LHZ                           1     00-LHZ   10-LHZ   20-LHZ
    // channels[1] = 00-LHND                          2     00-LHND  10-LHND  20-LHND
    // channels[2] = 00-LHED                          3     00-LHED  10-LHED  20-LHED
    // channels[3] = 10-LHZ                           
    // channels[4] = 10-LHND                          
    // channels[5] = 10-LHED                          
    // channels[6] = 20-LHZ                           
    // channels[7] = 20-LHND                         
    // channels[8] = 20-LHED                        

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

    if (channelData.size() != channels.length) {
        System.out.format("== plotZNE_3x3: Error: We have [%d channels] but [%d channelData]\n",
                channels.length, channelData.size());
        return;
    }

    XYSeries[] series = new XYSeries[channels.length];
    for (int i = 0; i < channels.length; i++) {
        series[i] = new XYSeries(channels[i].toString());
        double[] data = channelData.get(i);
        //for (int k = 0; k < xsecs.length; k++){
        for (int k = 0; k < data.length; k++) {
            series[i].add(xsecs[k], data[k]);
        }
    }

    // I. Panel I = Verticals

    // Use the first data array, within the plotted range (nstart - nend) to scale the plots:
    double[] data = channelData.get(0);
    double ymax = 0;
    for (int k = nstart; k < nend; k++) {
        if (data[k] > ymax)
            ymax = data[k];
    }

    final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    Paint[] paints = new Paint[] { Color.red, Color.blue, Color.green };
    for (int i = 0; i < paints.length; i++) {
        renderer.setSeriesPaint(i, paints[i]);
        renderer.setSeriesLinesVisible(i, true);
        renderer.setSeriesShapesVisible(i, false);
    }

    final NumberAxis verticalAxis = new NumberAxis("Displacement (m)");
    verticalAxis.setRange(new Range(-ymax, ymax));
    //verticalAxis.setTickUnit( new NumberTickUnit(5) );

    final NumberAxis horizontalAxis = new NumberAxis("Time (s)");
    horizontalAxis.setRange(new Range(nstart, nend));
    //horizontalAxis.setRange( new Range(0.00009 , 110) );
    final NumberAxis hAxis = new NumberAxis("Time (s)");
    hAxis.setRange(new Range(nstart, nend));

    final XYSeriesCollection seriesCollection1 = new XYSeriesCollection();
    seriesCollection1.addSeries(series[0]);
    seriesCollection1.addSeries(series[3]);
    seriesCollection1.addSeries(series[6]);
    //final XYPlot xyplot1 = new XYPlot((XYDataset)seriesCollection1, null, verticalAxis, renderer);
    //final XYPlot xyplot1 = new XYPlot((XYDataset)seriesCollection1, horizontalAxis, verticalAxis, renderer);
    final XYPlot xyplot1 = new XYPlot((XYDataset) seriesCollection1, hAxis, verticalAxis, renderer);
    double x = .95 * xsecs[nend];
    double y = .90 * ymax;
    XYTextAnnotation annotation1 = new XYTextAnnotation("Vertical", x, y);
    annotation1.setFont(new Font("SansSerif", Font.PLAIN, 14));
    xyplot1.addAnnotation(annotation1);

    // II. Panel II = North

    // Use the first data array, within the plotted range (nstart - nend) to scale the plots:
    data = channelData.get(1);
    ymax = 0;
    for (int k = nstart; k < nend; k++) {
        if (data[k] > ymax)
            ymax = data[k];
    }
    final NumberAxis verticalAxisN = new NumberAxis("Displacement (m)");
    verticalAxisN.setRange(new Range(-ymax, ymax));

    final XYSeriesCollection seriesCollection2 = new XYSeriesCollection();
    seriesCollection2.addSeries(series[1]);
    seriesCollection2.addSeries(series[4]);
    seriesCollection2.addSeries(series[7]);
    final XYPlot xyplot2 = new XYPlot((XYDataset) seriesCollection2, null, verticalAxisN, renderer);
    XYTextAnnotation annotation2 = new XYTextAnnotation("North-South", x, y);
    annotation2.setFont(new Font("SansSerif", Font.PLAIN, 14));
    xyplot2.addAnnotation(annotation2);

    // III. Panel III = East

    // Use the first data array, within the plotted range (nstart - nend) to scale the plots:
    data = channelData.get(2);
    ymax = 0;
    for (int k = nstart; k < nend; k++) {
        if (data[k] > ymax)
            ymax = data[k];
    }
    final NumberAxis verticalAxisE = new NumberAxis("Displacement (m)");
    verticalAxisE.setRange(new Range(-ymax, ymax));

    final XYSeriesCollection seriesCollection3 = new XYSeriesCollection();
    seriesCollection3.addSeries(series[2]);
    seriesCollection3.addSeries(series[5]);
    seriesCollection3.addSeries(series[8]);
    final XYPlot xyplot3 = new XYPlot((XYDataset) seriesCollection3, null, verticalAxisE, renderer);
    XYTextAnnotation annotation3 = new XYTextAnnotation("East-West", x, y);
    annotation3.setFont(new Font("SansSerif", Font.PLAIN, 14));
    xyplot3.addAnnotation(annotation3);

    //CombinedXYPlot combinedPlot = new CombinedXYPlot( horizontalAxis, CombinedXYPlot.VERTICAL );
    CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis);
    combinedPlot.add(xyplot1, 1);
    combinedPlot.add(xyplot2, 1);
    combinedPlot.add(xyplot3, 1);
    combinedPlot.setGap(15.);

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

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

    }

}

From source file:it.ferogrammer.ui.MainAppFrame.java

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
    if (jPanel2.getComponentCount() == 1 && (jPanel2.getComponent(0) instanceof ElectropherogramChartPanel)) {
        ElectropherogramChartPanel chartPanel = (ElectropherogramChartPanel) jPanel2.getComponent(0);
        final JFileChooser fc = new JFileChooser();
        //            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showSaveDialog(chartPanel);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            if (!file.getName().endsWith(".png")) {
                int extindex = file.getPath().indexOf('.') == -1 ? file.getPath().length()
                        : file.getPath().indexOf('.');
                file = new File(file.getPath().substring(0, extindex) + ".png");
            }//from w  w  w .j  a  v  a2s .  c  o  m
            try {
                ChartUtilities.saveChartAsPNG(file, chartPanel.getChart(), chartPanel.getWidth(),
                        chartPanel.getHeight());
            } catch (IOException ex) {
                JOptionPane op = new JOptionPane();
                op.showMessageDialog(jPanel2, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    } else {
        JOptionPane op = new JOptionPane();
        op.showMessageDialog(jPanel2, "Cannot export image", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:asl.util.PlotMaker2.java

public void writePlot(String fileName) {
    //System.out.format("== plotTitle=[%s] fileName=[%s]\n", plotTitle, fileName);

    File outputFile = new File(fileName);

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

    NumberAxis horizontalAxis = new NumberAxis("x-axis default"); // x = domain

    if (fileName.contains("nlnm") || fileName.contains("coher") || fileName.contains("stn")) { // NLNM or StationDeviation 
        horizontalAxis = new LogarithmicAxis("Period (sec)");
        horizontalAxis.setRange(new Range(1, 11000));
        horizontalAxis.setTickUnit(new NumberTickUnit(5.0));
    } else { // EventCompareSynthetics/StrongMotion
        horizontalAxis = new NumberAxis("Time (s)");
        double x[] = panels.get(0).getTraces().get(0).getxData();
        horizontalAxis.setRange(new Range(x[0], x[x.length - 1]));
    }

    CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis);
    combinedPlot.setGap(15.);

    // Loop over (3) panels for this plot:

    for (Panel panel : panels) {

        NumberAxis verticalAxis = new NumberAxis("y-axis default"); // y = range

        if (fileName.contains("nlnm") || fileName.contains("stn")) { // NLNM or StationDeviation 
            verticalAxis = new NumberAxis("PSD 10log10(m**2/s**4)/Hz dB");
            verticalAxis.setRange(new Range(-190, -95));
            verticalAxis.setTickUnit(new NumberTickUnit(5.0));
        } else if (fileName.contains("coher")) { // Coherence
            verticalAxis = new NumberAxis("Coherence, Gamma");
            verticalAxis.setRange(new Range(0, 1.2));
            verticalAxis.setTickUnit(new NumberTickUnit(0.1));
        } else { // EventCompareSynthetics/StrongMotion
            verticalAxis = new NumberAxis("Displacement (m)");
        }

        Font fontPlain = new Font("Verdana", Font.PLAIN, 14);
        Font fontBold = new Font("Verdana", Font.BOLD, 18);
        verticalAxis.setLabelFont(fontBold);
        verticalAxis.setTickLabelFont(fontPlain);
        horizontalAxis.setLabelFont(fontBold);
        horizontalAxis.setTickLabelFont(fontPlain);

        XYSeriesCollection seriesCollection = new XYSeriesCollection();
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, horizontalAxis, verticalAxis, renderer);
        xyplot.setDomainGridlinesVisible(true);
        xyplot.setRangeGridlinesVisible(true);
        xyplot.setRangeGridlinePaint(Color.black);
        xyplot.setDomainGridlinePaint(Color.black);

        // Plot each trace on this panel:
        int iTrace = 0;
        for (Trace trace : panel.getTraces()) {

            XYSeries series = new XYSeries(trace.getName());

            double xdata[] = trace.getxData();
            double ydata[] = trace.getyData();
            for (int k = 0; k < xdata.length; k++) {
                series.add(xdata[k], ydata[k]);
            }

            renderer.setSeriesPaint(iTrace, trace.getColor());
            renderer.setSeriesStroke(iTrace, trace.getStroke());
            renderer.setSeriesLinesVisible(iTrace, true);
            renderer.setSeriesShapesVisible(iTrace, false);

            seriesCollection.addSeries(series);

            iTrace++;
        }

        // Add Annotations for each trace - This is done in a separate loop so that
        //                      the upper/lower limits for this panel will be known
        double xmin = horizontalAxis.getRange().getLowerBound();
        double xmax = horizontalAxis.getRange().getUpperBound();
        double ymin = verticalAxis.getRange().getLowerBound();
        double ymax = verticalAxis.getRange().getUpperBound();
        double delX = Math.abs(xmax - xmin);
        double delY = Math.abs(ymax - ymin);

        // Annotation (x,y) in normalized units - where upper-right corner = (1,1)
        double xAnn = 0.97; // Right center coords of the trace name (e.g., "00-LHZ")
        double yAnn = 0.95;

        double yOff = 0.05; // Vertical distance between different trace legends

        iTrace = 0;
        for (Trace trace : panel.getTraces()) {
            if (!trace.getName().contains("NLNM") && !trace.getName().contains("NHNM")) {
                // x1 > x2 > x3, e.g.:
                //  o-------o   00-LHZ
                //  x3     x2       x1

                double scale = .01; // Controls distance between trace label and line segment
                double xL = .04; // Length of trace line segment in legend

                double xAnn2 = xAnn - scale * trace.getName().length();
                double xAnn3 = xAnn - scale * trace.getName().length() - xL;

                double x1 = xAnn * delX + xmin; // Right hand x-coord of text in range units
                double x2 = xAnn2 * delX + xmin; // x-coord of line segment end in range units
                double x3 = xAnn3 * delX + xmin; // x-coord of line segment end in range units

                double y = (yAnn - (iTrace * yOff)) * delY + ymin;

                if (horizontalAxis instanceof LogarithmicAxis) {
                    double logMin = Math.log10(xmin);
                    double logMax = Math.log10(xmax);
                    delX = logMax - logMin;
                    x1 = Math.pow(10, xAnn * delX + logMin);
                    x2 = Math.pow(10, xAnn2 * delX + logMin);
                    x3 = Math.pow(10, xAnn3 * delX + logMin);
                }
                xyplot.addAnnotation(new XYLineAnnotation(x3, y, x2, y, trace.getStroke(), trace.getColor()));
                XYTextAnnotation xyText = new XYTextAnnotation(trace.getName(), x1, y);
                xyText.setFont(new Font("Verdana", Font.BOLD, 18));
                xyText.setTextAnchor(TextAnchor.CENTER_RIGHT);
                xyplot.addAnnotation(xyText);
            }
            iTrace++;
        }

        combinedPlot.add(xyplot, 1);

    } // panel

    final JFreeChart chart = new JFreeChart(combinedPlot);
    chart.setTitle(new TextTitle(plotTitle, new Font("Verdana", Font.BOLD, 18)));
    chart.removeLegend();

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

    }

}

From source file:net.sf.maltcms.chromaui.project.spi.runnables.CondensePeakAnnotationsRunnable.java

private void saveHistogramChart(HistogramDataset dataset, File f) {
    String plotTitle = "Histogram";
    String xaxis = "similarity";
    String yaxis = "frequency";
    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);/*from w  ww .  j a  v  a  2 s.c  om*/
    //chart.getXYPlot().setRangeAxis(new LogarithmicAxis("Frequency"));
    XYBarRenderer sbr = new XYBarRenderer();
    //sbr.setBarAlignmentFactor(0.5);
    sbr.setBarPainter(new StandardXYBarPainter());
    sbr.setShadowVisible(false);
    chart.getXYPlot().setRenderer(sbr);
    ChartCustomizer.setSeriesColors(chart.getXYPlot(), 0.1f);
    int width = 800;
    int height = 600;
    try {
        ChartUtilities.saveChartAsPNG(f, chart, width, height);
    } catch (IOException e) {
    }
}

From source file:asl.plotmaker.PlotMaker2.java

public void writePlot(String fileName) {
    // System.out.format("== plotTitle=[%s] fileName=[%s]\n", plotTitle,
    // fileName);

    File outputFile = new File(fileName);

    // Check that we will be able to output the file without problems and if
    // not --> return
    if (!checkFileOut(outputFile)) {
        // System.out.format("== plotMaker: request to output plot=[%s] but we are unable to create it "
        // + " --> skip plot\n", fileName );
        logger.warn("== Request to output plot=[{}] but we are unable to create it " + " --> skip plot\n",
                fileName);//from ww  w  .  ja va2s. co m
        return;
    }

    NumberAxis horizontalAxis = new NumberAxis("x-axis default"); // x =
    // domain

    if (fileName.contains("alnm") || fileName.contains("nlnm") || fileName.contains("coher")
            || fileName.contains("stn")) { // NLNM or StationDeviation
        horizontalAxis = new LogarithmicAxis("Period (sec)");
        horizontalAxis.setRange(new Range(1, 11000));
        horizontalAxis.setTickUnit(new NumberTickUnit(5.0));
    } else { // EventCompareSynthetics/StrongMotion
        horizontalAxis = new NumberAxis("Time (s)");
        double x[] = panels.get(0).getTraces().get(0).getxData();
        horizontalAxis.setRange(new Range(x[0], x[x.length - 1]));
    }

    CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis);
    combinedPlot.setGap(15.);

    // Loop over (3) panels for this plot:

    for (Panel panel : panels) {

        NumberAxis verticalAxis = new NumberAxis("y-axis default"); // y =
        // range

        if (fileName.contains("alnm") || fileName.contains("nlnm") || fileName.contains("stn")) { // NLNM
            // or
            // StationDeviation
            verticalAxis = new NumberAxis("PSD 10log10(m**2/s**4)/Hz dB");
            verticalAxis.setRange(new Range(-190, -80));
            verticalAxis.setTickUnit(new NumberTickUnit(5.0));
        } else if (fileName.contains("coher")) { // Coherence
            verticalAxis = new NumberAxis("Coherence, Gamma");
            verticalAxis.setRange(new Range(0, 1.2));
            verticalAxis.setTickUnit(new NumberTickUnit(0.1));
        } else { // EventCompareSynthetics/StrongMotion
            verticalAxis = new NumberAxis("Displacement (m)");
        }

        Font fontPlain = new Font("Verdana", Font.PLAIN, 14);
        Font fontBold = new Font("Verdana", Font.BOLD, 18);
        verticalAxis.setLabelFont(fontBold);
        verticalAxis.setTickLabelFont(fontPlain);
        horizontalAxis.setLabelFont(fontBold);
        horizontalAxis.setTickLabelFont(fontPlain);

        XYSeriesCollection seriesCollection = new XYSeriesCollection();
        XYDotRenderer renderer = new XYDotRenderer();
        XYPlot xyplot = new XYPlot(seriesCollection, horizontalAxis, verticalAxis, renderer);
        xyplot.setDomainGridlinesVisible(true);
        xyplot.setRangeGridlinesVisible(true);
        xyplot.setRangeGridlinePaint(Color.black);
        xyplot.setDomainGridlinePaint(Color.black);

        // Plot each trace on this panel:
        int iTrace = 0;
        for (Trace trace : panel.getTraces()) {

            XYSeries series = new XYSeries(trace.getName());

            double xdata[] = trace.getxData();
            double ydata[] = trace.getyData();
            for (int k = 0; k < xdata.length; k++) {
                series.add(xdata[k], ydata[k]);
            }

            renderer.setSeriesPaint(iTrace, trace.getColor());
            renderer.setSeriesStroke(iTrace, trace.getStroke());

            seriesCollection.addSeries(series);

            iTrace++;
        }

        // Add Annotations for each trace - This is done in a separate loop
        // so that
        // the upper/lower limits for this panel will be known
        double xmin = horizontalAxis.getRange().getLowerBound();
        double xmax = horizontalAxis.getRange().getUpperBound();
        double ymin = verticalAxis.getRange().getLowerBound();
        double ymax = verticalAxis.getRange().getUpperBound();
        double delX = Math.abs(xmax - xmin);
        double delY = Math.abs(ymax - ymin);

        // Annotation (x,y) in normalized units - where upper-right corner =
        // (1,1)
        double xAnn = 0.97; // Right center coords of the trace name (e.g.,
        // "00-LHZ")
        double yAnn = 0.95;

        double yOff = 0.05; // Vertical distance between different trace
        // legends

        iTrace = 0;
        for (Trace trace : panel.getTraces()) {
            if (!trace.getName().contains("NLNM") && !trace.getName().contains("NHNM")
                    && !trace.getName().contains("ALNM")) {
                // x1 > x2 > x3, e.g.:
                // o-------o 00-LHZ
                // x3 x2 x1

                double scale = .01; // Controls distance between trace label
                // and line segment
                double xL = .04; // Length of trace line segment in legend

                double xAnn2 = xAnn - scale * trace.getName().length();
                double xAnn3 = xAnn - scale * trace.getName().length() - xL;

                double x1 = xAnn * delX + xmin; // Right hand x-coord of
                // text in range units
                double x2 = xAnn2 * delX + xmin; // x-coord of line segment
                // end in range units
                double x3 = xAnn3 * delX + xmin; // x-coord of line segment
                // end in range units

                double y = (yAnn - (iTrace * yOff)) * delY + ymin;

                if (horizontalAxis instanceof LogarithmicAxis) {
                    double logMin = Math.log10(xmin);
                    double logMax = Math.log10(xmax);
                    delX = logMax - logMin;
                    x1 = Math.pow(10, xAnn * delX + logMin);
                    x2 = Math.pow(10, xAnn2 * delX + logMin);
                    x3 = Math.pow(10, xAnn3 * delX + logMin);
                }
                xyplot.addAnnotation(new XYLineAnnotation(x3, y, x2, y, trace.getStroke(), trace.getColor()));
                XYTextAnnotation xyText = new XYTextAnnotation(trace.getName(), x1, y);
                xyText.setFont(new Font("Verdana", Font.BOLD, 18));
                xyText.setTextAnchor(TextAnchor.CENTER_RIGHT);
                xyplot.addAnnotation(xyText);
            }
            iTrace++;
        }

        combinedPlot.add(xyplot, 1);

    } // panel

    final JFreeChart chart = new JFreeChart(combinedPlot);
    chart.setTitle(new TextTitle(plotTitle, new Font("Verdana", Font.BOLD, 18)));
    chart.removeLegend();

    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, 1400, 1400);
    } catch (IOException e) {
        // System.err.println("Problem occurred creating chart.");
        logger.error("IOException:", e);
    }

}