Example usage for org.jfree.chart JFreeChart setBackgroundPaint

List of usage examples for org.jfree.chart JFreeChart setBackgroundPaint

Introduction

In this page you can find the example usage for org.jfree.chart JFreeChart setBackgroundPaint.

Prototype

public void setBackgroundPaint(Paint paint) 

Source Link

Document

Sets the paint used to fill the chart background and sends a ChartChangeEvent to all registered listeners.

Usage

From source file:org.jfree.chart.demo.ImageMapDemo3.java

/**
 * Starting point for the demo.//from w w  w .  java 2 s. c  om
 *
 * @param args  ignored.
 *
 * @throws ParseException if there is a problem parsing dates.
 */
public static void main(final String[] args) throws ParseException {

    //  Create a sample dataset
    final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
    final XYSeries dataSeries = new XYSeries("Curve data");
    final ArrayList toolTips = new ArrayList();
    dataSeries.add(sdf.parse("01-Jul-2002").getTime(), 5.22);
    toolTips.add("1D - 5.22");
    dataSeries.add(sdf.parse("02-Jul-2002").getTime(), 5.18);
    toolTips.add("2D - 5.18");
    dataSeries.add(sdf.parse("03-Jul-2002").getTime(), 5.23);
    toolTips.add("3D - 5.23");
    dataSeries.add(sdf.parse("04-Jul-2002").getTime(), 5.15);
    toolTips.add("4D - 5.15");
    dataSeries.add(sdf.parse("05-Jul-2002").getTime(), 5.22);
    toolTips.add("5D - 5.22");
    dataSeries.add(sdf.parse("06-Jul-2002").getTime(), 5.25);
    toolTips.add("6D - 5.25");
    dataSeries.add(sdf.parse("07-Jul-2002").getTime(), 5.31);
    toolTips.add("7D - 5.31");
    dataSeries.add(sdf.parse("08-Jul-2002").getTime(), 5.36);
    toolTips.add("8D - 5.36");
    final XYSeriesCollection xyDataset = new XYSeriesCollection(dataSeries);
    final CustomXYToolTipGenerator ttg = new CustomXYToolTipGenerator();
    ttg.addToolTipSeries(toolTips);

    //  Create the chart
    final StandardXYURLGenerator urlg = new StandardXYURLGenerator("xy_details.jsp");
    final ValueAxis timeAxis = new DateAxis("");
    final NumberAxis valueAxis = new NumberAxis("");
    valueAxis.setAutoRangeIncludesZero(false); // override default
    final XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, null);
    final StandardXYItemRenderer sxyir = new StandardXYItemRenderer(
            StandardXYItemRenderer.LINES + StandardXYItemRenderer.SHAPES, ttg, urlg);
    sxyir.setShapesFilled(true);
    plot.setRenderer(sxyir);
    final JFreeChart chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, false);
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("xychart100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("xychart100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"xychart100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

    } catch (IOException e) {
        System.out.println(e.toString());
    }
    return;
}

From source file:no.met.jtimeseries.marinogram.MarinogramWrapper.java

public static void main(String args[]) throws Exception {
    MarinogramTemperaturePlot mp = new MarinogramTemperaturePlot(800, 200, "UTC", "en");
    mp.setDescription("Temperature");

    MarinogramTemperaturePlot mp1 = new MarinogramTemperaturePlot(800, 200, "UTC", "en");
    mp1.setDescription("Temperature1");

    MarinogramPlot marinogram = new MarinogramWrapper(900, 200, "UTC", "en");
    marinogram.setDescription("marinogram");

    MarinogramWrapper marinogram1 = new MarinogramWrapper(940, 200, "UTC", "en");
    // /*from www  .j  a v a2s  .c o m*/
    // 30.95, 71.5
    // 58.9653, 5.7180
    //41.8947&longitude=12.4839
    //41.0138
    //5.04092, 58.89468 
    //16.66, 68.56 
    //10.72938, 71.50000 
    ChartPlottingInfo cpi = new ChartPlottingInfo.Builder(5.32905, 74.39825).width(mp1.getWidth())
            .showAirTemperature(true).showWaterTemperature(true).showDewpointTemperature(true)
            .showPressure(true).showWaveDirection(true).showWaveHeight(true).showCurrentDirection(true)
            .showCurrentSpeed(true).showWindDirection(true).showWindSpeed(true).timezone("UTC").language("en")
            .build();
    JFreeChart jchart = marinogram1.createMarinogram(cpi);
    jchart.setBorderVisible(false);
    Paint paint = new GradientPaint(0, 0, Color.WHITE, marinogram1.getWidth(), 0, Color.WHITE);
    jchart.setBackgroundPaint(paint);
    jchart.removeLegend();
    ChartFrame frame = new ChartFrame(jchart, new java.awt.Dimension(900, 400));
    frame.pack();
    frame.setVisible(true);
}

From source file:de.codesourcery.eve.skills.ui.ChartTest.java

public static void main(String[] args) {

    TimeSeries s1 = new TimeSeries("L&G European Index Trust");
    s1.add(new Day(1, 2, 2001), 181.8);
    s1.add(new Month(3, 2001), 167.3);
    s1.add(new Month(4, 2001), 153.8);
    s1.add(new Month(5, 2001), 167.6);
    s1.add(new Month(6, 2001), 158.8);
    s1.add(new Month(7, 2001), 148.3);
    s1.add(new Month(8, 2001), 153.9);
    s1.add(new Month(9, 2001), 142.7);
    s1.add(new Month(10, 2001), 123.2);
    s1.add(new Month(11, 2001), 131.8);
    s1.add(new Month(12, 2001), 139.6);
    s1.add(new Month(1, 2002), 142.9);
    s1.add(new Month(2, 2002), 138.7);
    s1.add(new Month(3, 2002), 137.3);
    s1.add(new Month(4, 2002), 143.9);
    s1.add(new Month(5, 2002), 139.8);
    s1.add(new Month(6, 2002), 137.0);
    s1.add(new Month(7, 2002), 132.8);
    TimeSeries s2 = new TimeSeries("L&G UK Index Trust");
    s2.add(new Month(2, 2001), 129.6);
    s2.add(new Month(3, 2001), 123.2);
    s2.add(new Month(4, 2001), 117.2);
    s2.add(new Month(5, 2001), 124.1);
    s2.add(new Month(6, 2001), 122.6);
    s2.add(new Month(7, 2001), 119.2);
    s2.add(new Month(8, 2001), 116.5);
    s2.add(new Month(9, 2001), 112.7);
    s2.add(new Month(10, 2001), 101.5);
    s2.add(new Month(11, 2001), 106.1);
    s2.add(new Month(12, 2001), 110.3);
    s2.add(new Month(1, 2002), 111.7);
    s2.add(new Month(2, 2002), 111.0);
    s2.add(new Month(3, 2002), 109.6);
    s2.add(new Month(4, 2002), 113.2);
    s2.add(new Month(5, 2002), 111.6);
    s2.add(new Month(6, 2002), 108.8);
    s2.add(new Month(7, 2002), 101.6);

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(s1);/*ww w  .  j a  v a2s. com*/
    dataset.addSeries(s2);

    JFreeChart chart = ChartFactory.createTimeSeriesChart("Legal & General Unit Trust Prices", // title
            "Date", // x-axis label
            "Price Per Unit", // y-axis label
            dataset, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );

    chart.setBackgroundPaint(Color.white);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);
    XYItemRenderer r = plot.getRenderer();
    if (r instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
        renderer.setBaseShapesVisible(true);
        renderer.setBaseShapesFilled(true);
    }
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));

    // display chart
    ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
    chartPanel.setMouseZoomable(true, false);

    JFrame frame = new JFrame("test");
    frame.setContentPane(chartPanel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

}

From source file:org.jfree.chart.demo.ImageMapDemo7.java

/**
 * Starting point for the demo./*  www.  ja va  2 s .c o  m*/
 *
 * @param args  ignored.
 */
public static void main(final String[] args) {

    final XYDataset data = new SampleXYDataset2();
    final JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot Demo", "X", "Y", data,
            PlotOrientation.VERTICAL, true, true, false);
    //        final Legend legend = chart.getLegend();
    //      if (legend instanceof StandardLegend) {
    //        final StandardLegend sl = (StandardLegend) legend;
    //      sl.setDisplaySeriesShapes(true);
    //}
    final NumberAxis domainAxis = (NumberAxis) chart.getXYPlot().getDomainAxis();
    domainAxis.setAutoRangeIncludesZero(false);
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("scatter100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("scatter100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"scatter100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

    } catch (IOException e) {
        System.out.println(e.toString());
    }

}

From source file:org.jfree.chart.demo.ImageMapDemo2.java

/**
 * The starting point for the demo.// w  w w. jav  a 2  s  .  c  o m
 *
 * @param args  ignored.
 */
public static void main(final String[] args) {

    // create a chart
    final DefaultPieDataset data = new DefaultPieDataset();
    data.setValue("One", new Double(43.2));
    data.setValue("Two", new Double(10.0));
    data.setValue("Three", new Double(27.5));
    data.setValue("Four", new Double(17.5));
    data.setValue("Five", new Double(11.0));
    data.setValue("Six", new Double(19.4));

    JFreeChart chart = null;
    final boolean drilldown = true;

    // create the chart...
    if (drilldown) {
        final PiePlot plot = new PiePlot(data);
        //          plot.setInsets(new Insets(0, 5, 5, 5));
        plot.setToolTipGenerator(new StandardPieItemLabelGenerator());
        plot.setURLGenerator(new StandardPieURLGenerator("pie_chart_detail.jsp"));
        chart = new JFreeChart("Pie Chart Demo 1", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    } else {
        chart = ChartFactory.createPieChart("Pie Chart Demo 1", // chart title
                data, // data
                true, // include legend
                true, false);
    }
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("piechart100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("piechart100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo 2</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"piechart100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

    } catch (IOException e) {
        System.out.println(e.toString());
    }

}

From source file:mzmatch.ipeak.normalisation.VanDeSompele.java

public static void main(String args[]) {
    try {//from   w ww.  ja va  2s .  c o  m
        Tool.init();

        // parse the commandline options
        Options options = new Options();
        CmdLineParser cmdline = new CmdLineParser(options);

        // check whether we need to show the help
        cmdline.parse(args);
        if (options.help) {
            Tool.printHeader(System.out, application, version);
            cmdline.printUsage(System.out, "");
            return;
        }

        if (options.verbose) {
            Tool.printHeader(System.out, application, version);
            cmdline.printOptions();
        }

        // check the command-line parameters
        {
            // if the output directories do not exist, create them
            if (options.output != null)
                Tool.createFilePath(options.output, true);
        }

        // load the data
        if (options.verbose)
            System.out.println("Loading data");
        ParseResult result = PeakMLParser.parse(new FileInputStream(options.input), true);

        Header header = result.header;
        IPeakSet<IPeakSet<? extends IPeak>> peaksets = (IPeakSet<IPeakSet<? extends IPeak>>) result.measurement;

        int nrmeasurements = header.getNrMeasurementInfos();

        // remove the stability factor annotation
        for (IPeak peak : peaksets)
            peak.removeAnnotation("stability factor");

        // load the database
        if (options.verbose)
            System.out.println("Loading the molecule database");
        HashMap<String, Molecule> database = MoleculeIO.parseXml(new FileInputStream(options.database));

        // filter the set to include only identifiable metabolites
        if (options.verbose)
            System.out.println("Creating selection");
        Vector<IPeakSet<? extends IPeak>> selection = new Vector<IPeakSet<? extends IPeak>>();
        for (Molecule molecule : database.values()) {
            double mass = molecule.getMass(Mass.MONOISOTOPIC);
            double delta = PeriodicTable.PPM(mass, options.ppm);

            // get the most intense peak containing all the measurements
            Vector<IPeakSet<? extends IPeak>> neighbourhoud = peaksets.getPeaksInMassRange(mass - delta,
                    mass + delta);
            Collections.sort(neighbourhoud, IPeak.sort_intensity_descending);
            for (IPeakSet<? extends IPeak> neighbour : neighbourhoud)
                if (count(neighbour) == nrmeasurements) {
                    selection.add(neighbour);
                    break;
                }
        }

        // calculate the stability factor for each peak in the selection
        if (options.verbose)
            System.out.println("Calculating stability factors");
        for (int peakid1 = 0; peakid1 < selection.size(); ++peakid1) {
            double stddeviations[] = new double[selection.size()];

            IPeakSet<? extends IPeak> peakset1 = selection.get(peakid1);
            for (int peakid2 = 0; peakid2 < selection.size(); ++peakid2) {
                IPeakSet<? extends IPeak> peakset2 = selection.get(peakid2);

                double values[] = new double[nrmeasurements];
                for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid) {
                    int measurementid1 = peakset1.get(measurementid).getMeasurementID();
                    int setid1 = header.indexOfSetInfo(header.getSetInfoForMeasurementID(measurementid1));
                    int measurementid2 = peakset2.get(measurementid).getMeasurementID();
                    int setid2 = header.indexOfSetInfo(header.getSetInfoForMeasurementID(measurementid2));
                    if (setid1 != setid2 || measurementid1 != measurementid2)
                        System.err.println("[WARNING]: differing setid or spectrumid for comparison");

                    values[measurementid] = Math.log(peakset1.get(measurementid).getIntensity()
                            / peakset2.get(measurementid).getIntensity()) / Math.log(2);
                }
                stddeviations[peakid2] = Statistical.stddev(values);
            }

            peakset1.addAnnotation("stability factor", Statistical.mean(stddeviations));
        }

        // sort on the stability factor
        Collections.sort(selection, new IPeak.AnnotationAscending("stability factor"));

        // take the top 10% and calculate the geometric mean
        if (options.verbose)
            System.out.println("Calculating normalisation factors");
        int nrselected = (int) (0.1 * selection.size());
        if (nrselected < 10)
            nrselected = (10 < selection.size() ? 10 : selection.size());
        double normalization_factors[] = new double[nrmeasurements];
        for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid) {
            double values[] = new double[nrselected];
            for (int i = 0; i < nrselected; ++i) {
                IPeak peak = selection.get(i).get(measurementid);
                values[i] = peak.getIntensity();
            }
            normalization_factors[measurementid] = Statistical.geomean(values);
        }

        // scale the found normalization factors
        double maxnf = Statistical.max(normalization_factors);
        for (int sampleid = 0; sampleid < nrmeasurements; ++sampleid)
            normalization_factors[sampleid] /= maxnf;

        // write the selection if needed
        if (options.selection != null) {
            if (options.verbose)
                System.out.println("Writing original selection data");

            PeakMLWriter.write(result.header, selection, null,
                    new GZIPOutputStream(new FileOutputStream(options.selection)), null);
        }

        // normalize all the peaks
        if (options.verbose)
            System.out.println("Normalizing all the entries");
        for (IPeakSet<? extends IPeak> peakset : peaksets) {
            for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid) {
                // TODO why did I do this again ?
                int id = 0;
                int setid = 0;
                int spectrumid = 0;
                for (int i = 0; i < header.getNrSetInfos(); ++i) {
                    SetInfo set = header.getSetInfos().get(i);

                    if (id + set.getNrMeasurementIDs() > measurementid) {
                        setid = i;
                        spectrumid = measurementid - id;
                        break;
                    } else
                        id += set.getNrMeasurementIDs();
                }

                MassChromatogram<Peak> masschromatogram = null;
                for (IPeak p : peakset) {
                    int mymeasurementid = p.getMeasurementID();
                    int mysetid = header.indexOfSetInfo(header.getSetInfoForMeasurementID(mymeasurementid));
                    if (mysetid == setid && mymeasurementid == spectrumid) {
                        masschromatogram = (MassChromatogram<Peak>) p;
                        break;
                    }
                }
                if (masschromatogram == null)
                    continue;

                for (IPeak peak : masschromatogram.getPeaks())
                    peak.setIntensity(peak.getIntensity() / normalization_factors[measurementid]);
            }
        }

        // write the selection if needed
        if (options.selection_normalized != null) {
            if (options.verbose)
                System.out.println("Writing the normalized selection data");

            PeakMLWriter.write(result.header, selection, null,
                    new GZIPOutputStream(new FileOutputStream(options.selection_normalized)), null);
        }

        // write the factors if needed
        if (options.factors != null) {
            if (options.verbose)
                System.out.println("Writing the normalization factors");

            PrintStream out = new PrintStream(options.factors);
            for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid)
                out.println(header.getMeasurementInfo(measurementid).getLabel() + "\t"
                        + normalization_factors[measurementid]);
        }

        // write the plot if needed
        if (options.img != null) {
            if (options.verbose)
                System.out.println("Writing the graph");

            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            JFreeChart linechart = ChartFactory.createLineChart(null, "measurement", "normalization factor",
                    dataset, PlotOrientation.VERTICAL, false, // legend
                    false, // tooltips
                    false // urls
            );

            CategoryPlot plot = (CategoryPlot) linechart.getPlot();
            CategoryAxis axis = (CategoryAxis) plot.getDomainAxis();
            axis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
            LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();

            renderer.setSeriesShapesFilled(0, true);
            renderer.setSeriesShapesVisible(0, true);

            linechart.setBackgroundPaint(Color.WHITE);
            linechart.setBorderVisible(false);
            linechart.setAntiAlias(true);

            plot.setBackgroundPaint(Color.WHITE);
            plot.setDomainGridlinesVisible(true);
            plot.setRangeGridlinesVisible(true);

            // create the datasets
            for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid)
                dataset.addValue(normalization_factors[measurementid], "",
                        header.getMeasurementInfo(measurementid).getLabel());
            JFreeChartTools.writeAsPDF(new FileOutputStream(options.img), linechart, 800, 500);
        }

        // write the normalized values
        if (options.verbose)
            System.out.println("Writing the normalized data");
        PeakMLWriter.write(result.header, peaksets.getPeaks(), null,
                new GZIPOutputStream(new FileOutputStream(options.output)), null);
    } catch (Exception e) {
        Tool.unexpectedError(e, application);
    }
}

From source file:org.jfree.chart.demo.ImageMapDemo1.java

/**
 * Starting point for the demo.//from   w  w  w .  java2 s.c om
 *
 * @param args  ignored.
 */
public static void main(final String[] args) {

    // create a chart
    final double[][] data = new double[][] { { 56.0, -12.0, 34.0, 76.0, 56.0, 100.0, 67.0, 45.0 },
            { 37.0, 45.0, 67.0, 25.0, 34.0, 34.0, 100.0, 53.0 },
            { 43.0, 54.0, 34.0, 34.0, 87.0, 64.0, 73.0, 12.0 } };
    final CategoryDataset dataset = DatasetUtilities.createCategoryDataset("Series ", "Type ", data);

    JFreeChart chart = null;
    final boolean drilldown = true;

    if (drilldown) {
        final CategoryAxis categoryAxis = new CategoryAxis("Category");
        final ValueAxis valueAxis = new NumberAxis("Value");
        final BarRenderer renderer = new BarRenderer();
        renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());
        renderer.setItemURLGenerator(new StandardCategoryURLGenerator("bar_chart_detail.jsp"));
        final CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer);
        plot.setOrientation(PlotOrientation.VERTICAL);
        chart = new JFreeChart("Bar Chart", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    } else {
        chart = ChartFactory.createBarChart("Vertical Bar Chart", // chart title
                "Category", // domain axis label
                "Value", // range axis label
                dataset, // data
                PlotOrientation.VERTICAL, true, // include legend
                true, false);
    }
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("barchart100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("barchart100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"barchart100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

    } catch (IOException e) {
        System.out.println(e.toString());
    }

}

From source file:org.jfree.chart.demo.ImageMapDemo4.java

/**
 * Starting point for the demo./*from   ww  w  .  j av  a  2s  .c o  m*/
 *
 * @param args  ignored.
 */
public static void main(final String[] args) {

    // create a chart
    final double[][] data = new double[][] { { 56.0, -12.0, 34.0, 76.0, 56.0, 100.0, 67.0, 45.0 },
            { 37.0, 45.0, 67.0, 25.0, 34.0, 34.0, 100.0, 53.0 },
            { 43.0, 54.0, 34.0, 34.0, 87.0, 64.0, 73.0, 12.0 } };
    final CategoryDataset dataset = DatasetUtilities.createCategoryDataset("Series ", "Type ", data);

    JFreeChart chart = null;
    final boolean drilldown = true;

    if (drilldown) {
        final CategoryAxis3D categoryAxis = new CategoryAxis3D("Category");
        final ValueAxis valueAxis = new NumberAxis3D("Value");
        final BarRenderer3D renderer = new BarRenderer3D();
        renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());
        renderer.setItemURLGenerator(new StandardCategoryURLGenerator("bar_chart_detail.jsp"));
        final CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer);
        plot.setOrientation(PlotOrientation.VERTICAL);
        chart = new JFreeChart("Bar Chart", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    } else {
        chart = ChartFactory.createBarChart3D("Bar Chart", // chart title
                "Category", // domain axis label
                "Value", // range axis label
                dataset, // data
                PlotOrientation.VERTICAL, true, // include legend
                true, false);
    }
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("barchart101.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("barchart101.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"barchart100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

    } catch (IOException e) {
        System.out.println(e.toString());
    }

}

From source file:mzmatch.ipeak.align.CowCoda.java

@SuppressWarnings("unchecked")
public static void main(String args[]) {
    final String lbl_mcq = "mcq";

    try {/* w w  w  . j a v a 2s.com*/
        Tool.init();

        // parse the commandline options
        final Options options = new Options();
        CmdLineParser cmdline = new CmdLineParser(options);

        // check whether we need to show the help
        cmdline.parse(args);
        if (options.help) {
            Tool.printHeader(System.out, application, version);
            cmdline.printUsage(System.out, "");
            return;
        }

        if (options.verbose) {
            Tool.printHeader(System.out, application, version);
            cmdline.printOptions();
        }

        // check the command-line parameters
        int filetype = JFreeChartTools.PDF;
        {
            if (options.ppm == -1) {
                System.err.println("[ERROR]: the ppm-value needs to be set.");
                System.exit(0);
            }
            if (options.order == -1) {
                System.err.println("[ERROR]: the order for the polynomial fit needs to be set.");
                System.exit(0);
            }
            if (options.maxrt == -1) {
                System.err.println("[ERROR]: the maximum retention time shift is not set.");
                System.exit(0);
            }

            if (options.image != null) {
                String extension = options.image.substring(options.image.lastIndexOf('.') + 1);
                if (extension.toLowerCase().equals("png"))
                    filetype = JFreeChartTools.PNG;
                else if (extension.toLowerCase().equals("pdf"))
                    filetype = JFreeChartTools.PDF;
                else {
                    System.err.println(
                            "[ERROR]: file extension of the image file needs to be either PDF or PNG.");
                    System.exit(0);
                }
            }

            // if the output directories do not exist, create them
            if (options.output != null)
                Tool.createFilePath(options.output, true);
            if (options.image != null)
                Tool.createFilePath(options.image, true);
            if (options.selection != null)
                Tool.createFilePath(options.selection, true);
        }

        // load the data
        if (options.verbose)
            System.out.println("Loading the data");
        double maxrt = 0;
        Vector<ParseResult> data = new Vector<ParseResult>();
        Vector<IPeakSet<IPeak>> matchdata = new Vector<IPeakSet<IPeak>>();
        for (String file : options.input) {
            System.out.println("- " + new File(file).getName());

            // load the mass chromatogram data
            ParseResult result = PeakMLParser.parse(new FileInputStream(file), true);
            data.add(result);

            // select the best mass chromatograms
            Vector<IPeak> selection = new Vector<IPeak>();
            for (IPeak peak : (IPeakSet<IPeak>) result.measurement) {
                maxrt = Math.max(maxrt, maxRT(peak));

                double mcq = codaDW(peak);
                peak.addAnnotation(lbl_mcq, Double.toString(mcq), Annotation.ValueType.DOUBLE);
                if (mcq >= options.codadw)
                    selection.add(peak);
            }

            // keep track of the selected mass chromatograms
            int id = options.input.indexOf(file);
            IPeakSet<IPeak> peakset = new IPeakSet<IPeak>(selection);
            peakset.setMeasurementID(id);
            for (IPeak mc : peakset)
                mc.setMeasurementID(id);
            matchdata.add(peakset);
        }

        // match the selection together
        if (options.verbose)
            System.out.println("Matching the data");
        Vector<IPeakSet<IPeak>> matches = IPeak.match((Vector) matchdata, options.ppm,
                new IPeak.MatchCompare<IPeak>() {
                    public double distance(IPeak peak1, IPeak peak2) {
                        double diff = Math.abs(peak1.getRetentionTime() - peak2.getRetentionTime());
                        if (diff > options.maxrt)
                            return -1;

                        Signal signal1 = new Signal(peak1.getSignal());
                        signal1.normalize();
                        Signal signal2 = new Signal(peak2.getSignal());
                        signal2.normalize();

                        double offset = bestOffSet(peak1, peak2, options.maxrt);
                        for (int i = 0; i < signal2.getSize(); ++i)
                            signal2.getX()[i] += offset;

                        double correlation = signal2
                                .pearsonsCorrelation(signal1)[Statistical.PEARSON_CORRELATION];
                        if (correlation < 0.5)
                            return -1;

                        // the match-function optimizes toward 0 (it's a distance)
                        return 1 - correlation;
                    }
                });

        // filter out all incomplete sets
        Vector<IPeakSet<IPeak>> valids = new Vector<IPeakSet<IPeak>>();
        for (IPeakSet<IPeak> set : matches) {
            if (set.size() < options.input.size())
                continue;
            valids.add((IPeakSet) set);
        }

        // calculate the alignment factors
        if (options.verbose)
            System.out.println("Calculating the alignment factors");
        double medians[] = new double[valids.size() + 2];
        DataFrame.Double dataframe = new DataFrame.Double(valids.size() + 2, options.input.size());

        medians[0] = 0;
        medians[medians.length - 1] = maxrt;
        for (int i = 0; i < options.input.size(); ++i) {
            dataframe.set(0, i, 0.1);
            dataframe.set(dataframe.getNrRows() - 1, i, 0);
        }

        for (int matchid = 0; matchid < valids.size(); ++matchid) {
            IPeakSet<IPeak> match = valids.get(matchid);

            // find the most central
            double offsets[][] = new double[match.size()][match.size()];
            for (int i = 0; i < match.size(); ++i)
                for (int j = i + 1; j < match.size(); ++j) {
                    offsets[i][j] = bestOffSet(match.get(i), match.get(j), options.maxrt);
                    offsets[j][i] = -offsets[i][j];
                }

            int besti = 0;
            double bestabssum = Double.MAX_VALUE;
            for (int i = 0; i < match.size(); ++i) {
                double abssum = 0;
                for (int j = 0; j < match.size(); ++j)
                    abssum += Math.abs(offsets[i][j]);
                if (abssum < bestabssum) {
                    besti = i;
                    bestabssum = abssum;
                }
            }

            for (int i = 0; i < match.size(); ++i)
                dataframe.set(matchid + 1, match.get(i).getMeasurementID(),
                        (i == besti ? 0 : offsets[i][besti]));

            medians[matchid + 1] = match.get(besti).getRetentionTime();
            dataframe.setRowName(matchid, Double.toString(match.get(besti).getRetentionTime()));
        }
        double minmedian = Statistical.min(medians);
        double maxmedian = Statistical.max(medians);

        // calculate for each profile the correction function
        PolynomialFunction functions[] = new PolynomialFunction[valids.size()];
        for (int i = 0; i < options.input.size(); ++i)
            functions[i] = PolynomialFunction.fit(options.order, medians, dataframe.getCol(i));

        // make a nice plot out of the whole thing
        if (options.verbose)
            System.out.println("Writing results");
        if (options.image != null) {
            org.jfree.data.xy.XYSeriesCollection dataset = new org.jfree.data.xy.XYSeriesCollection();
            JFreeChart linechart = ChartFactory.createXYLineChart(null, "Retention Time (seconds)", "offset",
                    dataset, PlotOrientation.VERTICAL, true, // legend
                    false, // tooltips
                    false // urls
            );

            // setup the colorkey
            Colormap colormap = new Colormap(Colormap.EXCEL);

            // get the structure behind the graph
            XYPlot plot = (XYPlot) linechart.getPlot();
            XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();

            // setup the plot area
            linechart.setBackgroundPaint(java.awt.Color.WHITE);
            linechart.setBorderVisible(false);
            linechart.setAntiAlias(true);

            plot.setBackgroundPaint(java.awt.Color.WHITE);
            plot.setDomainGridlinesVisible(true);
            plot.setRangeGridlinesVisible(true);

            // create the datasets
            for (int i = 0; i < options.input.size(); ++i) {
                org.jfree.data.xy.XYSeries series = new org.jfree.data.xy.XYSeries(dataframe.getColName(i));
                org.jfree.data.xy.XYSeries function = new org.jfree.data.xy.XYSeries(
                        dataframe.getColName(i) + "-function");
                dataset.addSeries(series);
                dataset.addSeries(function);

                renderer.setSeriesPaint(dataset.getSeriesCount() - 1, new java.awt.Color(colormap.getColor(i)));
                renderer.setSeriesPaint(dataset.getSeriesCount() - 2, new java.awt.Color(colormap.getColor(i)));

                renderer.setSeriesLinesVisible(dataset.getSeriesCount() - 2, false);
                renderer.setSeriesShapesVisible(dataset.getSeriesCount() - 2, true);

                // add the data-points
                for (int j = 0; j < valids.size(); ++j)
                    series.add(medians[j], dataframe.get(j, i));
                for (double x = minmedian; x < maxmedian; ++x)
                    function.add(x, functions[i].getY(x));
            }

            dataset.removeAllSeries();
            for (int i = 0; i < options.input.size(); ++i) {
                Function function = functions[i];

                org.jfree.data.xy.XYSeries series = new org.jfree.data.xy.XYSeries(dataframe.getColName(i));
                dataset.addSeries(series);

                renderer.setSeriesPaint(i, new java.awt.Color(colormap.getColor(i)));
                renderer.setSeriesLinesVisible(i, false);
                renderer.setSeriesShapesVisible(i, true);

                // add the data-points
                for (int j = 0; j < valids.size(); ++j)
                    series.add(medians[j], dataframe.get(j, i) - function.getY(medians[j]));
            }

            JFreeChartTools.writeAs(filetype, new FileOutputStream(options.image), linechart, 800, 500);
        }

        // save the selected
        if (options.selection != null) {
            Header header = new Header();

            // set the number of peaks to be stored
            header.setNrPeaks(valids.size());

            // create a set for the measurements
            SetInfo set = new SetInfo("", SetInfo.SET);
            header.addSetInfo(set);

            // create the measurement infos
            for (int i = 0; i < options.input.size(); ++i) {
                String file = options.input.get(i);

                // create the measurement info
                MeasurementInfo measurement = new MeasurementInfo(i, data.get(i).header.getMeasurementInfo(0));
                measurement.addFileInfo(new FileInfo(file, file));

                header.addMeasurementInfo(measurement);

                // add the file to the set
                set.addChild(new SetInfo(file, SetInfo.SET, i));
            }

            // write the data
            PeakMLWriter.write(header, (Vector) valids, null,
                    new GZIPOutputStream(new FileOutputStream(options.selection)), null);
        }

        // correct the values with the found function and save them
        for (int i = 0; i < options.input.size(); ++i) {
            Function function = functions[i];
            ParseResult result = data.get(i);

            IPeakSet<MassChromatogram<Peak>> peakset = (IPeakSet<MassChromatogram<Peak>>) result.measurement;
            for (IPeak peak : peakset)
                align(peak, function);

            File filename = new File(options.input.get(i));
            String name = filename.getName();

            PeakMLWriter.write(result.header, (Vector) peakset.getPeaks(), null,
                    new GZIPOutputStream(new FileOutputStream(options.output + "/" + name)), null);
        }
    } catch (Exception e) {
        Tool.unexpectedError(e, application);
    }
}

From source file:org.jfree.chart.demo.XIntervalSeriesCollectionDemo1.java

private static JFreeChart createChart(IntervalXYDataset intervalxydataset) {
    DateAxis dateaxis = new DateAxis("Date");
    NumberAxis numberaxis = new NumberAxis("Y");
    XYBarRenderer xybarrenderer = new XYBarRenderer();
    xybarrenderer.setUseYInterval(true);
    XYPlot xyplot = new XYPlot(intervalxydataset, dateaxis, numberaxis, xybarrenderer);
    JFreeChart jfreechart = new JFreeChart(xyplot);
    jfreechart.setBackgroundPaint(Color.white);
    xyplot.setBackgroundPaint(Color.lightGray);
    xyplot.setDomainGridlinePaint(Color.white);
    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.white);
    return jfreechart;
}