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.samjoey.graphing.GraphUtility.java

/**
 *
 * @param games the games to graph//from w  w  w. j  av a 2 s.c  om
 * @param key the variable to create the graph with
 * @param start if index, the index at which to start, else the percent in
 * the game at which to start
 * @param stop if index, the index at which to end, else the percent in the
 * game at which to end
 * @param index
 * @return
 */
public static ChartPanel getCustomGraph(Game[] games, String key, double start, double stop, boolean index) {
    XYSeriesCollection dataset = new XYSeriesCollection();
    for (Game game : games) {
        ArrayList<Double> data = game.getVar(key);
        int begin;
        int end;
        if (index) {
            begin = (int) start;
            end = (int) stop;
        } else {
            begin = (int) (data.size() / start);
            end = (int) (data.size() / stop);
        }
        XYSeries series = GraphUtility.createSeries(data.subList(begin, end), "" + game.getId());
        dataset.addSeries(series);
    }
    JFreeChart chart = ChartFactory.createXYLineChart(key, // chart title
            "X", // x axis label
            "Y", // y axis label
            dataset, // data
            PlotOrientation.VERTICAL, false, // include legend
            true, // tooltips
            false // urls
    );
    XYPlot plot = chart.getXYPlot();
    XYItemRenderer rend = plot.getRenderer();
    for (int i = 0; i < games.length; i++) {
        Game g = games[i];
        if (g.getWinner() == 1) {
            rend.setSeriesPaint(i, Color.RED);
        }
        if (g.getWinner() == 2) {
            rend.setSeriesPaint(i, Color.BLACK);
        }
        if (g.getWinner() == 0) {
            rend.setSeriesPaint(i, Color.PINK);
        }
    }
    ChartPanel chartPanel = new ChartPanel(chart);
    return chartPanel;
}

From source file:org.hxzon.demo.jfreechart.OtherDatasetDemo.java

private static XYDataset createPolarDataset() {
    boolean notify = false;
    XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries series1 = new XYSeries("series 1");
    //(theta,radius)
    for (int i = 0; i < 20; i++) {
        series1.add(i * 10, i * 10, notify);
    }/* w  ww  .  j  av a  2  s. c o  m*/
    dataset.addSeries(series1);
    return dataset;
}

From source file:org.xapagy.ui.tempdyn.GraphEvolution.java

/**
 * Generates the graph which plots the three choice scores (independent,
 * dependent and mood) for the evolution of a choice in time.
 * /*from   w  ww . j  a  va  2 s. c om*/
 * @param tdc
 *            - encompasses the selected choice
 * @param database
 *            - the database of values collected
 * @param agent
 * @param index
 *            - a list of time points which will be plotted on the x axis
 * @param choiceRange
 *            - the y axis will be [0, choiceRange]
 */
public static void graphChoiceEvolution(tdComponent tdc, tdDataBase database, Agent agent, List<Double> index,
        double choiceRange) {
    String label = PpChoice.ppConcise(tdc.getChoice(), agent);

    // create a general purpose xy collection for jfreechart
    XYSeriesCollection xysc = new XYSeriesCollection();
    // focus and memory
    xysc.addSeries(new XYSeries("ChoiceScoreIndependent"));
    xysc.addSeries(new XYSeries("ChoiceScoreDependent"));
    xysc.addSeries(new XYSeries("ChoiceScoreMood"));
    // Fill in the values
    for (Double time : index) {
        double dtime = time;
        double valueChoiceScoreIndependent = database.getChoiceScoreDependent(tdc.getIdentifier(), time);
        xysc.getSeries("ChoiceScoreIndependent").add(dtime, valueChoiceScoreIndependent);
        double valueChoiceScoreDependent = database.getChoiceScoreDependent(tdc.getIdentifier(), time);
        xysc.getSeries("ChoiceScoreDependent").add(dtime, valueChoiceScoreDependent);
        double valueChoiceScoreMood = database.getChoiceScoreDependent(tdc.getIdentifier(), time);
        xysc.getSeries("ChoiceScoreMood").add(dtime, valueChoiceScoreMood);
    }
    //
    // ok, now let us create a graph
    //
    JPanel panel = new JPanel();
    // create a layout
    GroupLayout layout = new GroupLayout(panel);
    panel.setLayout(layout);
    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);
    SequentialGroup sgv = layout.createSequentialGroup();
    layout.setVerticalGroup(sgv);
    ParallelGroup pgh = layout.createParallelGroup();
    layout.setHorizontalGroup(pgh);
    //
    // the graph with the focus and the memory
    //
    XYSeriesCollection xysFM = new XYSeriesCollection();
    xysFM.addSeries(xysc.getSeries("ChoiceScoreIndependent"));
    xysFM.addSeries(xysc.getSeries("ChoiceScoreDependent"));
    xysFM.addSeries(xysc.getSeries("ChoiceScoreMood"));
    JFreeChart chart = ChartFactory.createXYLineChart(label + " - Choice", "Time", "Value", xysFM,
            PlotOrientation.VERTICAL, true, false, false);
    GraphEvolution.setChartProperties(chart, GraphEvolution.lineStylesColorful);
    ChartPanel cp = new ChartPanel(chart);
    sgv.addComponent(cp);
    pgh.addComponent(cp);
    JFrame frame = new JFrame();
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
}

From source file:gda.util.SavePNGPlot.java

/**
 * //ww w .  java  2  s .  c om
 * @param imageFile
 * @param scan
 * @param width
 * @param height
 * @param chartTitle
 * @throws IOException
 */
public static void save(String imageFile, ScanFileHolder scan, int width, int height, String chartTitle)
        throws IOException {

    final XYSeriesCollection dataset = new XYSeriesCollection();

    XYSeries series;

    IDataset x_axis = scan.getAxis(0);

    String[] headings = scan.getHeadings();
    String yAxisName;
    if (headings.length == 2)
        yAxisName = headings[1];
    else
        yAxisName = "various";

    for (int seriesNum = 1; seriesNum < headings.length; seriesNum++) {
        series = new XYSeries("");
        for (int point = 0, max = x_axis.getSize(); point < max - 1; point++)
            series.add(x_axis.getDouble(point), scan.getAxis(seriesNum).getDouble(point));
        series.setKey(headings[seriesNum]);
        dataset.addSeries(series);
    }

    final JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, // chart
            // title
            headings[0], // x axis label
            yAxisName, // y axis label
            dataset, // data
            PlotOrientation.VERTICAL, true, // include legend
            false, // tool tips
            false // url's
    );
    ChartUtilities.saveChartAsPNG(new File(imageFile), chart, width, height);
}

From source file:simulador.controle.GraficoCategorias.java

private static XYSeriesCollection criarDataset(Map<String, Map<Float, Float>> dadosRadios) {

    if (DEBUG) {//w w w  .  j a  va  2 s  .c  o  m
        System.out.println("GraficoRadiais.criarDataset");
    }

    XYSeriesCollection colecaoParesXY = new XYSeriesCollection();

    for (Map.Entry<String, Map<Float, Float>> parDadosRadios : dadosRadios.entrySet()) {

        Map<Float, Float> dadosRadio = parDadosRadios.getValue();
        XYSeries paresXY = new XYSeries(parDadosRadios.getKey());

        for (Map.Entry<Float, Float> parDadosRadio : dadosRadio.entrySet()) {

            float d = parDadosRadio.getKey();
            float p = parDadosRadio.getValue();

            //System.out.println("d = "+d);
            //System.out.println("p = "+p);

            paresXY.add(parDadosRadio.getKey(), parDadosRadio.getValue());

        }

        colecaoParesXY.addSeries(paresXY);

    }

    return colecaoParesXY;

}

From source file:oct.util.Util.java

public static void graphPoints(List<LinePoint>... pointsList) {
    XYSeriesCollection dataset = new XYSeriesCollection();
    int seriesCntr = 1;
    for (List<LinePoint> points : pointsList) {
        XYSeries data = new XYSeries("Series " + seriesCntr);
        points.forEach((point) -> {/*from  www . jav a 2  s.c  om*/
            data.add(point.getX(), point.getY());
        });
        dataset.addSeries(data);
        seriesCntr++;
    }

    JFrame graphFrame = new JFrame("Points graph");

    JPanel chartPanel = createChartPanel("Points graph", dataset);
    graphFrame.add(chartPanel, BorderLayout.SOUTH);
    SwingUtilities.invokeLater(() -> {
        graphFrame.pack();
        graphFrame.setVisible(true);
    });
}

From source file:com.jolbox.benchmark.BenchmarkMain.java

/**
 * @param results/*  ww  w . jav a  2s  . c  om*/
 * @param delay 
 * @param statementBenchmark 
 * @param noC3P0 
 */
private static void doPlotLineGraph(long[][] results, int delay, boolean statementBenchmark, boolean noC3P0) {
    XYSeriesCollection dataset = new XYSeriesCollection();
    for (int i = 0; i < ConnectionPoolType.values().length; i++) { //
        if (!ConnectionPoolType.values()[i].isEnabled()
                || (noC3P0 && ConnectionPoolType.values()[i].equals(ConnectionPoolType.C3P0))) {
            continue;
        }
        XYSeries series = new XYSeries(ConnectionPoolType.values()[i].toString());

        for (int j = 1 + BenchmarkTests.stepping; j < results[i].length; j += BenchmarkTests.stepping) {
            series.add(j, results[i][j]);
        }
        dataset.addSeries(series);
    }

    //         Generate the graph
    String title = "Multi-Thread test (" + delay + "ms delay)";
    if (statementBenchmark) {
        title += "\n(with PreparedStatements tests)";
    }
    JFreeChart chart = ChartFactory.createXYLineChart(title, // Title
            "threads", // x-axis Label
            "time (ns)", // y-axis Label
            dataset, // Dataset
            PlotOrientation.VERTICAL, // Plot Orientation
            true, // Show Legend
            true, // Use tooltips
            false // Configure chart to generate URLs?
    );

    XYPlot plot = (XYPlot) chart.getPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
    plot.setRenderer(renderer);
    renderer.setSeriesPaint(0, Color.BLUE);
    renderer.setSeriesPaint(1, Color.YELLOW);
    renderer.setSeriesPaint(2, Color.BLACK);
    renderer.setSeriesPaint(3, Color.DARK_GRAY);
    renderer.setSeriesPaint(4, Color.MAGENTA);
    renderer.setSeriesPaint(5, Color.RED);
    renderer.setSeriesPaint(6, Color.LIGHT_GRAY);
    //          renderer.setSeriesShapesVisible(1, true);   
    //          renderer.setSeriesShapesVisible(2, true);   

    try {
        String fname = System.getProperty("java.io.tmpdir") + File.separator + "bonecp-multithread-" + delay
                + "ms-delay";
        if (statementBenchmark) {
            fname += "-with-preparedstatements";
        }
        fname += "-poolsize-" + BenchmarkTests.pool_size + "-threads-" + BenchmarkTests.threads;
        if (noC3P0) {
            fname += "-noC3P0";
        }
        fname += ".png";
        ChartUtilities.saveChartAsPNG(new File(fname), chart, 1024, 768);
        System.out.println("******* Saved chart to: " + fname);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }

}

From source file:de.bfs.radon.omsimulation.gui.data.OMCharts.java

/**
 * Creates a chart displaying the radon concentration of a single room. Uses
 * red for normal rooms, blue for cellar rooms and green for misc rooms.
 * //from w w  w  .  j  av a2 s. c  om
 * @param title
 *          The headline of the chart. Will be hidden if set to null.
 * @param room
 *          The room object containing the radon data.
 * @param preview
 *          Will hide annotations, labels and headlines if true.
 * @return A chart displaying the radon concentration of a single room.
 */
public static JFreeChart createRoomChart(String title, OMRoom room, boolean preview) {
    Color lineColor = new Color(0, 0, 0, 128);
    Color rangeColor = new Color(222, 222, 222, 128);
    if (room.getType() == OMRoomType.Room) {
        lineColor = new Color(255, 0, 0, 128);
        rangeColor = new Color(255, 222, 222, 128);
    } else {
        if (room.getType() == OMRoomType.Cellar) {
            lineColor = new Color(0, 0, 255, 128);
            rangeColor = new Color(222, 222, 255, 128);
        } else {
            lineColor = new Color(0, 128, 0, 255);
            rangeColor = new Color(222, 255, 222, 128);
        }
    }
    double[] values = room.getValues();
    XYSeriesCollection dataSet = new XYSeriesCollection();
    XYSeries series = new XYSeries("Radon");
    int count = room.getCount();
    double maxPointerKey = 0;
    for (int i = 0; i < count; i++) {
        series.add(i, values[i]);
        if (values[i] == room.getMaximum()) {
            maxPointerKey = i;
        }
    }
    dataSet.addSeries(series);
    title = title + ": " + room.getType().toString() + " " + room.getId();
    JFreeChart chart = ChartFactory.createXYLineChart(title, "T [h]", "Rn [Bq/m\u00B3]", dataSet,
            PlotOrientation.VERTICAL, false, true, false);
    XYPlot plot = (XYPlot) chart.getPlot();
    double positiveDeviation = room.getAverage() + room.getDeviation();
    double negativeDeviation = room.getAverage() - room.getDeviation();
    IntervalMarker deviation = new IntervalMarker(negativeDeviation, positiveDeviation);
    float[] dash = { 5, 3 };
    deviation.setPaint(rangeColor);
    deviation.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, dash, 0));
    plot.addRangeMarker(deviation, Layer.BACKGROUND);
    ValueMarker arithMarker = new ValueMarker(room.getAverage(), lineColor,
            new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, dash, 0));
    plot.addRangeMarker(arithMarker);
    ValueMarker maxiMarker = new ValueMarker(room.getMaximum(), lineColor,
            new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, dash, 0));
    plot.addRangeMarker(maxiMarker);
    XYTextAnnotation amLabel = new XYTextAnnotation("AM=" + (int) room.getAverage(), count,
            room.getAverage() * 1.01);
    plot.addAnnotation(amLabel);
    XYTextAnnotation sdLabel = new XYTextAnnotation("SD=" + (int) room.getDeviation(), count,
            (room.getAverage() + room.getDeviation()) * 1.01);
    plot.addAnnotation(sdLabel);
    XYTextAnnotation maxLabel = new XYTextAnnotation("MAX=" + (int) room.getMaximum(), count,
            room.getMaximum() * 1.01);
    plot.addAnnotation(maxLabel);
    XYPointerAnnotation maxPointer = new XYPointerAnnotation("", maxPointerKey, room.getMaximum(),
            Math.PI * 1.1);
    plot.addAnnotation(maxPointer);
    XYItemRenderer renderer = plot.getRenderer();
    renderer.setSeriesPaint(0, lineColor);
    if (preview) {
        chart.setTitle("");
        plot.clearAnnotations();
    }
    return chart;
}

From source file:lu.lippmann.cdb.datasetview.tabs.ScatterPlotTabView.java

private static ChartPanel buildChartPanel(final Instances dataSet, final int xidx, final int yidx,
        final int coloridx, final boolean asSerie) {
    final XYSeriesCollection data = new XYSeriesCollection();
    final Map<Integer, List<Instance>> filteredInstances = new HashMap<Integer, List<Instance>>();
    final int classIndex = dataSet.classIndex();
    if (classIndex < 0) {
        final XYSeries series = new XYSeries("Serie", false);
        for (int i = 0; i < dataSet.numInstances(); i++) {
            series.add(dataSet.instance(i).value(xidx), dataSet.instance(i).value(yidx));

        }/*  ww w.  j  a va  2 s  .c o  m*/
        data.addSeries(series);
    } else {
        final Set<String> pvs = WekaDataStatsUtil.getPresentValuesForNominalAttribute(dataSet, classIndex);
        int p = 0;
        for (final String pv : pvs) {
            final XYSeries series = new XYSeries(pv, false);
            for (int i = 0; i < dataSet.numInstances(); i++) {
                if (dataSet.instance(i).stringValue(classIndex).equals(pv)) {
                    if (!filteredInstances.containsKey(p)) {
                        filteredInstances.put(p, new ArrayList<Instance>());
                    }
                    filteredInstances.get(p).add(dataSet.instance(i));

                    series.add(dataSet.instance(i).value(xidx), dataSet.instance(i).value(yidx));
                }
            }
            data.addSeries(series);

            p++;
        }

    }

    final JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot", // chart title
            dataSet.attribute(xidx).name(), // x axis label
            dataSet.attribute(yidx).name(), // y axis label
            data, // data
            PlotOrientation.VERTICAL, true, // include legend
            true, // tooltips
            false // urls
    );

    final XYPlot xyPlot = (XYPlot) chart.getPlot();
    final XYToolTipGenerator gen = new XYToolTipGenerator() {
        @Override
        public String generateToolTip(final XYDataset dataset, final int series, final int item) {
            if (classIndex < 0) {
                return InstanceFormatter.htmlFormat(dataSet.instance(item), true);
            } else {
                return InstanceFormatter.htmlFormat(filteredInstances.get(series).get(item), true);
            }
        }
    };

    int nbSeries;
    if (classIndex < 0) {
        nbSeries = 1;
    } else {
        nbSeries = filteredInstances.keySet().size();
    }

    final XYItemRenderer renderer = new XYLineAndShapeRenderer(asSerie, true) {
        /** */
        private static final long serialVersionUID = 1L;

        @Override
        public Paint getItemPaint(final int row, final int col) {
            //System.out.println(row+" "+col);
            if (classIndex < 0) {
                final double v = dataSet.instance(col).value(coloridx);
                final double[] minmax = WekaDataStatsUtil.getMinMaxForAttributeAsArrayOfDoubles(dataSet,
                        coloridx);

                final double rated = (v - minmax[0]) / (minmax[1] - minmax[0]);
                System.out.println("rated -> " + rated + " min=" + minmax[0] + "max=" + minmax[1]);
                final int colorIdx = (int) Math.round((ColorHelper.YlGnBu_9_COLORS.length - 1) * rated);

                //System.out.println(minmax[0]+" "+minmax[1]+" "+v+" "+rated+" "+colorIdx);
                return ColorHelper.YlGnBu_9_COLORS[colorIdx];
            } else
                return super.getItemPaint(row, col);
        }
    };
    xyPlot.setRenderer(renderer);

    for (int i = 0; i < nbSeries; i++) {
        renderer.setSeriesToolTipGenerator(i, gen);
    }

    return new ChartPanel(chart);
}

From source file:org.matsim.contrib.socnetsim.usage.analysis.CourtesyHistogramListener.java

static JFreeChart getGraphic(final CourtesyHistogram.DataFrame dataFrame, int iteration, String actType) {
    final XYSeriesCollection xyData = new XYSeriesCollection();
    final XYSeries helloSeries = new XYSeries("hello", false, true);
    final XYSeries goodbyeSerie = new XYSeries("goodbye", false, true);
    final XYSeries togetherSerie = new XYSeries("pairs together", false, true);
    int together = 0;
    for (int i = 0; i < dataFrame.countsHello.length; i++) {
        together = together + dataFrame.countsHello[i] - dataFrame.countsGoodbye[i];
        double hour = i * dataFrame.binSize / 60.0 / 60.0;
        helloSeries.add(hour, dataFrame.countsHello[i]);
        goodbyeSerie.add(hour, dataFrame.countsGoodbye[i]);
        togetherSerie.add(hour, together);
    }//  www  .j a v  a  2 s  . c o m

    xyData.addSeries(helloSeries);
    xyData.addSeries(goodbyeSerie);
    xyData.addSeries(togetherSerie);

    final JFreeChart chart = ChartFactory.createXYStepChart(
            "Courtesy Statistics," + "actType " + actType + " it." + iteration, "time", "# persons", xyData,
            PlotOrientation.VERTICAL, true, // legend
            false, // tooltips
            false // urls
    );

    XYPlot plot = chart.getXYPlot();

    final CategoryAxis axis1 = new CategoryAxis("hour");
    axis1.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 7));
    plot.setDomainAxis(new NumberAxis("time"));

    plot.getRenderer().setSeriesStroke(0, new BasicStroke(2.0f));
    plot.getRenderer().setSeriesStroke(1, new BasicStroke(2.0f));
    plot.getRenderer().setSeriesStroke(2, new BasicStroke(2.0f));
    plot.setBackgroundPaint(Color.white);
    plot.setRangeGridlinePaint(Color.gray);
    plot.setDomainGridlinePaint(Color.gray);

    return chart;
}