Example usage for org.jfree.data.xy XYSeriesCollection addSeries

List of usage examples for org.jfree.data.xy XYSeriesCollection addSeries

Introduction

In this page you can find the example usage for org.jfree.data.xy XYSeriesCollection addSeries.

Prototype

public void addSeries(XYSeries series) 

Source Link

Document

Adds a series to the collection and sends a DatasetChangeEvent to all registered listeners.

Usage

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

public static void main(String args[]) {
    XYSeries xyseries = new XYSeries("Series 1");
    xyseries.add(1.0D, 1.0D);/*from ww  w  .j a va2s  .  c o m*/
    xyseries.add(2D, 3D);
    xyseries.add(3D, 2D);
    xyseries.add(4D, 4D);
    XYSeriesCollection xyseriescollection = new XYSeriesCollection();
    xyseriescollection.addSeries(xyseries);
    JFreeChart jfreechart = ChartFactory.createXYLineChart(null, "X", "Y", xyseriescollection,
            PlotOrientation.VERTICAL, false, false, false);
    XYPlot xyplot = (XYPlot) jfreechart.getPlot();
    xyplot.setInsets(RectangleInsets.ZERO_INSETS);
    xyplot.setDomainGridlinesVisible(false);
    xyplot.setRangeGridlinesVisible(false);
    xyplot.setOutlinePaint(null);
    xyplot.getDomainAxis().setVisible(false);
    xyplot.getRangeAxis().setVisible(false);
    try {
        ChartUtilities.saveChartAsPNG(new File("Sparky.png"), jfreechart, 100, 20);
    } catch (IOException ioexception) {
        ioexception.printStackTrace();
    }
}

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

public static void main(String args[]) {
    XYSeries xyseries = new XYSeries("Advisory Range");
    xyseries.add(new Integer(1200), new Integer(1));
    xyseries.add(new Integer(1500), new Integer(1));
    XYSeries xyseries1 = new XYSeries("Normal Range");
    xyseries1.add(new Integer(2000), new Integer(4));
    xyseries1.add(new Integer(2300), new Integer(4));
    XYSeries xyseries2 = new XYSeries("Recommended");
    xyseries2.add(new Integer(2100), new Integer(2));
    XYSeries xyseries3 = new XYSeries("Current");
    xyseries3.add(new Integer(2400), new Integer(3));
    XYSeriesCollection xyseriescollection = new XYSeriesCollection();
    xyseriescollection.addSeries(xyseries);
    xyseriescollection.addSeries(xyseries1);
    xyseriescollection.addSeries(xyseries2);
    xyseriescollection.addSeries(xyseries3);
    JFreeChart jfreechart = ChartFactory.createXYLineChart("My Chart", "Calories", "Y", xyseriescollection,
            PlotOrientation.VERTICAL, true, true, false);
    StandardXYItemRenderer standardxyitemrenderer = new StandardXYItemRenderer(3, null);
    XYPlot xyplot = (XYPlot) jfreechart.getPlot();
    xyplot.setRenderer(standardxyitemrenderer);
    ValueAxis valueaxis = xyplot.getRangeAxis();
    valueaxis.setTickLabelsVisible(false);
    valueaxis.setRange(0.0D, 5D);/*from w  w  w  .ja  v a  2s .  c o m*/
    ChartFrame chartframe = new ChartFrame("Test", jfreechart);
    chartframe.pack();
    chartframe.setVisible(true);
}

From source file:Trabalho_1.java

/**
 * @param args the command line arguments
 *///from w ww.  j  ava  2s  . c  om
public static void main(String[] args) {
    // TODO code application logic here
    Ambiente n = new Ambiente(51, 51);
    n.inicializa(100, 30);

    XYSeries series = new XYSeries("Lobos");
    XYSeries series1 = new XYSeries("Ovelhas");
    XYSeries series2 = new XYSeries("Vegetacao");

    for (int i = 0; i < 5000; i++) {
        n.iteracao(i);

        series.add(i, n.getLobos());
        series1.add(i, n.getOvelhas());
        series2.add(i, n.getVegetacao());

    }

    // Add the series to your data set
    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series);
    dataset.addSeries(series1);
    dataset.addSeries(series2);

    XYSeriesCollection dataset2 = new XYSeriesCollection();
    dataset2.addSeries(series);
    dataset2.addSeries(series1);

    // Generate the graph
    JFreeChart chart = ChartFactory.createXYLineChart("Lobos, Ovelhas e Vegetacao", "Iteracoes",
            "Numero de Animais", dataset, PlotOrientation.VERTICAL, // Plot Orientation
            true, // Show Legend
            true, // Use tooltips
            false // Configure chart to generate URLs?
    );
    try {
        ChartUtilities.saveChartAsJPEG(new File("Grafico.jpg"), chart, 640, 480);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }

    // Generate the graph
    JFreeChart chart2 = ChartFactory.createXYLineChart("Lobos e ovelhas", "Iteracoes", "Numero de Animais",
            dataset2, PlotOrientation.VERTICAL, // Plot Orientation
            true, // Show Legend
            true, // Use tooltips
            false // Configure chart to generate URLs?
    );
    try {
        ChartUtilities.saveChartAsJPEG(new File("Grafico2.jpg"), chart2, 640, 480);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }
}

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

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

    // create some data...
    final XYSeries series1 = new XYSeries("Advisory Range");
    series1.add(new Integer(1200), new Integer(1));
    series1.add(new Integer(1500), new Integer(1));

    final XYSeries series2 = new XYSeries("Normal Range");
    series2.add(new Integer(2000), new Integer(4));
    series2.add(new Integer(2300), new Integer(4));

    final XYSeries series3 = new XYSeries("Recommended");
    series3.add(new Integer(2100), new Integer(2));

    final XYSeries series4 = new XYSeries("Current");
    series4.add(new Integer(2400), new Integer(3));

    final XYSeriesCollection data = new XYSeriesCollection();
    data.addSeries(series1);
    data.addSeries(series2);
    data.addSeries(series3);
    data.addSeries(series4);

    // create a chart...
    final JFreeChart chart = ChartFactory.createXYLineChart("My Chart", "Calories", "Y", data,
            PlotOrientation.VERTICAL, true, true, false);

    // ****************************************************************************
    // * 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.             *
    // ****************************************************************************

    final XYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES_AND_LINES, null);
    final XYPlot plot = (XYPlot) chart.getPlot();
    plot.setRenderer(renderer);
    final ValueAxis axis = plot.getRangeAxis();
    axis.setTickLabelsVisible(false);
    axis.setRange(0.0, 5.0);

    // create and display a frame...
    final ChartFrame frame = new ChartFrame("Test", chart);
    frame.pack();
    frame.setVisible(true);

}

From source file:pl.dpbz.poid.zadanie3.Main.java

public static void main(String args[]) throws UnsupportedAudioFileException, IOException {
    //Zassanie pliku
    File f = new File("ExampleSounds/artificial/easy/100Hz.wav");
    Integer[] ints = WaveToSamplesConverter.convertWaveToIntSamples(f);
    double samplingFrequency = WaveToSamplesConverter.getSamplingFrequency(f);

    //Zwyky sound, ktry nie potrzebuje zespolonych elementw
    Sound s = new Sound(ints, samplingFrequency);

    //Obliczenie czstotliwoci przy pomocy fazwki
    PhaseSpaceMultiDimensional pS = new PhaseSpaceMultiDimensional(s);
    pS.setupPhaseSpace();//from   w  w w .  j a v  a2  s. co  m
    pS.computeFrequency();
    System.out.println("Phase space " + pS.getFrequency());

    //Zespolony dwik, ktry jest bardziej zoony
    ComplexSound cs = new ComplexSound(ints, samplingFrequency, 15);
    //To oblicza fouriera
    cs.setupElementsOfComplexSound();
    //Tutaj obliczanie czstotliwoci przy pomocy fouriera
    CombFiltering cf = new CombFiltering(cs, samplingFrequency);
    cf.computeFrequency();
    cf.drawComplexSound();
    System.out.println("Comb Filtering " + cf.getFrequency());

    //Przy sekwencjach nie ma majstrowania przy ustawieniach, uytkownik
    // zmiennie moe podawa tylko liczb prbek, reszt jak czstotliwo prbkowania
    // i audio format pobiera si z otwieranego pliku

    //Test sekwencji na fazie
    File file = new File("ExampleSounds/seq/DWK_violin.wav");
    Integer[] seqInte = WaveToSamplesConverter.convertWaveToIntSamples(file);
    System.out.println("Samples overview " + seqInte.length);
    double seqSamplingFrequency = WaveToSamplesConverter.getSamplingFrequency(file);
    int samplesPerPart = 3000;
    SamplesToWaveConverter conv = new PhaseSpaceSampleConverter(seqSamplingFrequency, samplesPerPart,
            WaveToSamplesConverter.getAudioFormat(file));

    conv.setupFrequenciesFromSamples(seqInte);
    System.out.println("Zapisuj");
    conv.saveGeneratedSamples("XDPhase.wav");

    //Test sekwencji na grzebieniu
    SamplesToWaveConverter conv2 = new CombFilteringSampleConverter(seqSamplingFrequency, samplesPerPart,
            WaveToSamplesConverter.getAudioFormat(file));

    conv2.setupFrequenciesFromSamples(seqInte);
    System.out.println("Zapisuj");
    conv2.saveGeneratedSamples("XDComb.wav");

    //Rysowanie wykresu sygnau dwikowego
    final XYSeries dist = new XYSeries("P0");
    int index = 0;
    for (Integer i : ints) {
        dist.add(index / samplingFrequency, i);
        index++;
    }
    final XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(dist);

    JFreeChart chart = ChartFactory.createXYLineChart(f.getName(), "index", "Distance", dataset,
            PlotOrientation.VERTICAL, true, true, false);
    XYPlot xyPlot = (XYPlot) chart.getPlot();
    xyPlot.setDomainCrosshairVisible(true);
    xyPlot.setRangeCrosshairVisible(true);
    XYItemRenderer renderer = xyPlot.getRenderer();
    renderer.setSeriesPaint(0, Color.blue);
    NumberAxis domain = (NumberAxis) xyPlot.getRangeAxis();
    domain.setRange(-32768, 32768);
    ChartDrawer.drawChart(chart);

    System.out.println("FINISHED");
}

From source file:interpolation.Polyfit.java

public static void main(String[] args) {

    final ArrayList<Pair<Integer, Double>> mts = loadsimple(
            new File("/Users/varunkapoor/Documents/Ines_Fourier/Cell39.txt"));

    final ArrayList<Pair<Integer, Double>> mtspoly = new ArrayList<Pair<Integer, Double>>();

    double[] x = new double[mts.size()];
    double[] y = new double[mts.size()];

    int i = 0;// w w  w . j a  v  a2 s .  com
    for (Pair<Integer, Double> point : mts) {

        x[i] = point.getA();
        y[i] = point.getB();
        i++;
    }
    int degree = 20;
    Polyfit regression = new Polyfit(x, y, degree);
    for (double t = x[0]; t <= x[x.length - 1]; ++t) {
        double poly = regression.predict(t);

        mtspoly.add(new ValuePair<Integer, Double>((int) t, poly));
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(Tracking.drawPoints(mtspoly, new double[] { 1, 1, 1 }, "Function fit"));
    dataset.addSeries(Tracking.drawPoints(mts, new double[] { 1, 1, 1 }, "Original Data"));

    JFreeChart chart = Tracking.makeChart(dataset);
    Tracking.display(chart, new Dimension(500, 400));
    Tracking.setColor(chart, i, new Color(255, 0, 0));
    Tracking.setStroke(chart, i, 0.5f);

    for (int j = degree; j >= 0; --j)
        System.out.println(regression.GetCoefficients(j) + " *x power  " + j);
}

From source file:visualize.Visualize.java

public static void main(String[] args) throws NotEnoughDataPointsException, IllDefinedDataPointsException {
    XYSeries seriesQ = new XYSeries("quadratic");
    XYSeries seriesL = new XYSeries("linear");
    XYSeries seriesI = new XYSeries("intepolated");

    final ArrayList<Point> pointsQ = new ArrayList<Point>();

    for (double x = -5.0; x <= 5.0; x = x + 0.5)
        pointsQ.add(new Point(new double[] { x, 2.0 * x * x * x - 10 * x * x }));

    final LinearFunction fl = new LinearFunction();
    final HigherOrderPolynomialFunction fq = new HigherOrderPolynomialFunction(3);
    final InterpolatedPolynomial<LinearFunction, HigherOrderPolynomialFunction> fi = new InterpolatedPolynomial<LinearFunction, HigherOrderPolynomialFunction>(
            new LinearFunction(), fq.copy(), 0.5);

    fl.fitFunction(pointsQ);// w w  w .  j  a  va  2  s. co  m
    fq.fitFunction(pointsQ);
    fi.fitFunction(pointsQ);

    System.out.println(fl);
    System.out.println(fq);
    System.out.println(fi.interpolatedFunction);

    for (double x = -5.0; x <= 5.0; x = x + 0.5) {
        seriesQ.add(x, fq.predict(x));
        seriesL.add(x, fl.predict(x));
        seriesI.add(x, fi.predict(x));
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(seriesQ);
    dataset.addSeries(seriesL);
    dataset.addSeries(seriesI);

    JFreeChart chart = ChartFactory.createXYLineChart("XY Chart", "x-axis", "y-axis", dataset,
            PlotOrientation.VERTICAL, true, true, false);

    final XYPlot plot = chart.getXYPlot();
    final XYItemRenderer renderer = plot.getRenderer();
    renderer.setSeriesPaint(0, new Color(0, 0, 255));
    renderer.setSeriesStroke(0, new BasicStroke(0.5f));
    renderer.setSeriesPaint(1, new Color(255, 0, 0));
    renderer.setSeriesStroke(1, new BasicStroke(0.5f));
    renderer.setSeriesPaint(2, new Color(0, 200, 40));
    renderer.setSeriesStroke(2, new BasicStroke(1.5f));

    //chart.getXYPlot().setRenderer(new XYSplineRenderer(100));

    JPanel panel = new JPanel();
    ChartPanel chartPanel = new ChartPanel(chart);
    panel.add(chartPanel);

    JFrame frame = new JFrame();
    frame.setContentPane(panel);
    frame.validate();
    Dimension d = new Dimension(800, 500);
    frame.setSize(d);

    frame.setVisible(true);

    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("starting");

    for (int lambda = 0; lambda <= 100; ++lambda) {
        fi.setLambda(lambda / 100.0);
        fi.fitFunction(pointsQ);
        System.out.println(fi.interpolatedFunction);

        dataset.getSeries(2).clear();
        for (double x = -5.0; x <= 5.0; x = x + 0.5)
            seriesI.add(x, fi.predict(x));

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //   makeScreenshot( lambda );
    }

}

From source file:Graph_with_jframe_and_arduino.java

public static void main(String[] args) {

    // create and configure the window
    JFrame window = new JFrame();
    window.setTitle("Sensor Graph GUI");
    window.setSize(600, 400);// w w w  .  j  av a 2  s  . co m
    window.setLayout(new BorderLayout());
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // create a drop-down box and connect button, then place them at the top of the window
    JComboBox<String> portList_combobox = new JComboBox<String>();
    Dimension d = new Dimension(300, 100);
    portList_combobox.setSize(d);
    JButton connectButton = new JButton("Connect");
    JPanel topPanel = new JPanel();
    topPanel.add(portList_combobox);
    topPanel.add(connectButton);
    window.add(topPanel, BorderLayout.NORTH);
    //pause button
    JButton Pause_btn = new JButton("Start");

    // populate the drop-down box
    SerialPort[] portNames;
    portNames = SerialPort.getCommPorts();
    //check for new port available
    Thread thread_port = new Thread() {
        @Override
        public void run() {
            while (true) {
                SerialPort[] sp = SerialPort.getCommPorts();
                if (sp.length > 0) {
                    for (SerialPort sp_name : sp) {
                        int l = portList_combobox.getItemCount(), i;
                        for (i = 0; i < l; i++) {
                            //check port name already exist or not
                            if (sp_name.getSystemPortName().equalsIgnoreCase(portList_combobox.getItemAt(i))) {
                                break;
                            }
                        }
                        if (i == l) {
                            portList_combobox.addItem(sp_name.getSystemPortName());
                        }

                    }

                } else {
                    portList_combobox.removeAllItems();

                }
                portList_combobox.repaint();

            }

        }

    };
    thread_port.start();
    for (SerialPort sp_name : portNames)
        portList_combobox.addItem(sp_name.getSystemPortName());

    //for(int i = 0; i < portNames.length; i++)
    //   portList.addItem(portNames[i].getSystemPortName());

    // create the line graph
    XYSeries series = new XYSeries("line 1");
    XYSeries series2 = new XYSeries("line 2");
    XYSeries series3 = new XYSeries("line 3");
    XYSeries series4 = new XYSeries("line 4");
    for (int i = 0; i < 100; i++) {
        series.add(x, 0);
        series2.add(x, 0);
        series3.add(x, 0);
        series4.add(x, 10);
        x++;
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series);
    dataset.addSeries(series2);
    XYSeriesCollection dataset2 = new XYSeriesCollection();
    dataset2.addSeries(series3);
    dataset2.addSeries(series4);

    //create jfree chart
    JFreeChart chart = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading",
            dataset);
    JFreeChart chart2 = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading 2",
            dataset2);

    //color render for chart 1
    XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer();
    r1.setSeriesPaint(0, Color.RED);
    r1.setSeriesPaint(1, Color.GREEN);
    r1.setSeriesShapesVisible(0, false);
    r1.setSeriesShapesVisible(1, false);

    XYPlot plot = chart.getXYPlot();
    plot.setRenderer(0, r1);
    plot.setRenderer(1, r1);

    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.DARK_GRAY);
    plot.setRangeGridlinePaint(Color.blue);

    //color render for chart 2
    XYLineAndShapeRenderer r2 = new XYLineAndShapeRenderer();
    r2.setSeriesPaint(0, Color.BLUE);
    r2.setSeriesPaint(1, Color.ORANGE);
    r2.setSeriesShapesVisible(0, false);
    r2.setSeriesShapesVisible(1, false);

    XYPlot plot2 = chart2.getXYPlot();
    plot2.setRenderer(0, r2);
    plot2.setRenderer(1, r2);

    ChartPanel cp = new ChartPanel(chart);
    ChartPanel cp2 = new ChartPanel(chart2);

    //multiple graph container
    JPanel graph_container = new JPanel();
    graph_container.setLayout(new BoxLayout(graph_container, BoxLayout.X_AXIS));
    graph_container.add(cp);
    graph_container.add(cp2);

    //add chart panel in main window
    window.add(graph_container, BorderLayout.CENTER);
    //window.add(cp2, BorderLayout.WEST);

    window.add(Pause_btn, BorderLayout.AFTER_LAST_LINE);
    Pause_btn.setEnabled(false);
    //pause btn action
    Pause_btn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (Pause_btn.getText().equalsIgnoreCase("Pause")) {

                if (chosenPort.isOpen()) {
                    try {
                        Output.write(0);
                    } catch (IOException ex) {
                        Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }

                Pause_btn.setText("Start");
            } else {
                if (chosenPort.isOpen()) {
                    try {
                        Output.write(1);
                    } catch (IOException ex) {
                        Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }

                Pause_btn.setText("Pause");
            }
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });

    // configure the connect button and use another thread to listen for data
    connectButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (connectButton.getText().equals("Connect")) {
                // attempt to connect to the serial port
                chosenPort = SerialPort.getCommPort(portList_combobox.getSelectedItem().toString());
                chosenPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
                if (chosenPort.openPort()) {
                    Output = chosenPort.getOutputStream();
                    connectButton.setText("Disconnect");
                    Pause_btn.setEnabled(true);
                    portList_combobox.setEnabled(false);
                }

                // create a new thread that listens for incoming text and populates the graph
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        Scanner scanner = new Scanner(chosenPort.getInputStream());
                        while (scanner.hasNextLine()) {
                            try {
                                String line = scanner.nextLine();
                                int number = Integer.parseInt(line);
                                series.add(x, number);
                                series2.add(x, number / 2);
                                series3.add(x, number / 1.5);
                                series4.add(x, number / 5);

                                if (x > 100) {
                                    series.remove(0);
                                    series2.remove(0);
                                    series3.remove(0);
                                    series4.remove(0);
                                }

                                x++;
                                window.repaint();
                            } catch (Exception e) {
                            }
                        }
                        scanner.close();
                    }
                };
                thread.start();
            } else {
                // disconnect from the serial port
                chosenPort.closePort();
                portList_combobox.setEnabled(true);
                Pause_btn.setEnabled(false);
                connectButton.setText("Connect");

            }
        }
    });

    // show the window
    window.setVisible(true);
}

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

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

    try {/*from   ww w .  java2 s.  c  om*/
        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.GridBandDemo1.java

public static JPanel createDemoPanel() {
    XYSeries xyseries = new XYSeries("Random Data");
    for (int i = 0; i < 100; i++)
        xyseries.add(Math.random() + 1.0D, Math.random() + 1.0D);

    XYSeriesCollection xyseriescollection = new XYSeriesCollection();
    xyseriescollection.addSeries(xyseries);
    JFreeChart jfreechart = createChart(xyseriescollection);
    ChartPanel chartpanel = new ChartPanel(jfreechart);
    return chartpanel;
}