Example usage for org.jfree.data.time TimeSeriesCollection TimeSeriesCollection

List of usage examples for org.jfree.data.time TimeSeriesCollection TimeSeriesCollection

Introduction

In this page you can find the example usage for org.jfree.data.time TimeSeriesCollection TimeSeriesCollection.

Prototype

public TimeSeriesCollection() 

Source Link

Document

Constructs an empty dataset, tied to the default timezone.

Usage

From source file:com.bdb.weather.display.freeplot.FreePlotSeriesCollection.java

/**
 * Constructor.//from  w ww.j a v a 2s .c  o m
 * 
 * @param groupName The name of this group
 * @param units The units of this collection, used to setup the Range Axis
 * @param datasetIndex The dataset index from a JFreePlot perspective
 * @param domainAxisIndex The index of the domain axis, from a JFreeChart perspective
 * @param plot The plot to which the dataset and axis will be added
 * @param stroke The Stroke used to draw the series of this collection
 * @param factory The factory used to create the series
 */
FreePlotSeriesCollection(String groupName, Unit units, int datasetIndex, int domainAxisIndex, XYPlot plot,
        Stroke stroke, SeriesFactory<T> factory) {
    this.groupName = groupName;
    this.dataset = new TimeSeriesCollection();
    this.datasetIndex = datasetIndex;
    this.factory = factory;
    this.plot = plot;
    renderer = new DefaultXYItemRenderer();
    renderer.setBaseShapesVisible(false);
    renderer.setBaseToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());
    renderer.setDrawSeriesLineAsPath(true);
    plot.setDataset(datasetIndex, dataset);
    plot.setRenderer(datasetIndex, renderer);
    series = factory.createSeriesGroup(groupName, stroke);
    plot.mapDatasetToDomainAxis(datasetIndex, domainAxisIndex);
}

From source file:com.dreikraft.axbo.timeseries.TimeSeriesUtil.java

/**
 * Create a XYIntervalDataset from sleep data.
 *
 * @param sleepData the sleep data//from   www . j  av a2 s.  c o m
 * @param title the dataset title
 * @return a dataset
 */
public static final IntervalXYDataset createDataset(final SleepData sleepData, final String title) {
    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    final SleepDataTimeSeries sleepDataTimeSeries = new SleepDataTimeSeries(title, sleepData, Minute.class,
            Axbo.MAX_MOVEMENTS_DEFAULT);
    dataset.addSeries(sleepDataTimeSeries);
    return dataset;
}

From source file:edu.fullerton.viewerplugin.TsPlot.java

@Override
public ArrayList<Integer> makePlot(ArrayList<ChanDataBuffer> dbufs, boolean compact) throws WebUtilException {
    int imageId;/*from   w  ww  .  j a  v  a2 s.c o  m*/
    try {
        if (parameterMap.containsKey("ts_newplt")) {
            imageId = makeAddPlotFiles(dbufs, compact);
        } else {
            String gtitle = getTitle(dbufs, compact);

            XYSeriesCollection xyds = new XYSeriesCollection();
            TimeSeriesCollection mtds = new TimeSeriesCollection();

            compact = dbufs.size() > 2 ? false : compact;
            for (ChanDataBuffer dbuf : dbufs) {
                if (timeAxis.equalsIgnoreCase("utc")) {
                    addTimeSeries(dbuf, compact, mtds);
                } else {
                    addXySeries(dbuf, compact, xyds);
                }
            }
            Double minx, miny, maxx, maxy;
            Double[] rng = new Double[4];

            if (timeAxis.equalsIgnoreCase("utc")) {
                PluginSupport.getRangeLimits(mtds, rng);
            } else {
                PluginSupport.getRangeLimits(xyds, rng, 0);
            }
            minx = rng[0];
            miny = rng[1];
            maxx = rng[2];
            maxy = rng[3];

            int exp;
            if (timeAxis.equalsIgnoreCase("utc")) {
                exp = PluginSupport.scaleRange(mtds, miny, maxy);
            } else {
                exp = PluginSupport.scaleRange(xyds, miny, maxy);
            }

            ChartPanel cpnl;
            DefaultXYDataset ds = new DefaultXYDataset();
            JFreeChart chart;
            if (timeAxis.equalsIgnoreCase("utc")) {
                chart = ChartFactory.createTimeSeriesChart(gtitle, "Time (UTC)", "Amplitude (Counts)", ds, true,
                        true, false);
            } else {
                chart = ChartFactory.createXYLineChart(gtitle, xAxisLabel, "Amplitude (Counts)", ds,
                        PlotOrientation.VERTICAL, true, false, false);
            }

            XYPlot plot = (XYPlot) chart.getPlot();
            NumberAxis rangeAxis = new NumberAxis("Amplitude (Counts)");
            ScaledAxisNumberFormat sanf = new ScaledAxisNumberFormat();
            sanf.setExp(exp);
            if (maxy != 0 && Math.abs(maxy - miny) <= Math.abs(maxy) * 1e-25) {
                // this garbage is to get jFreeChart to put labels on the Y axis
                double dt = Math.abs(miny) / 10;
                double scaledMin = (miny - dt) * Math.pow(10., exp);
                double scaledMax = (maxy + dt) * Math.pow(10., exp);
                rangeAxis.setRange(scaledMin, scaledMax);
                NumberTickUnit unit = new NumberTickUnit((scaledMax - scaledMin) / 10.);
                rangeAxis.setTickUnit(unit);
                rangeAxis.setAutoRange(false);
            }
            //                else
            //                {
            //                    sanf.setMinMax(miny, maxy);
            //                    rangeAxis.setRange(miny, maxy);
            //                    NumberTickUnit unit = new NumberTickUnit((maxy  - miny)/6.);
            //                    rangeAxis.setTickUnit(unit);
            //                    rangeAxis.setAutoRange(false);
            //                }
            rangeAxis.setNumberFormatOverride(sanf);
            rangeAxis.setAutoRangeIncludesZero(false);
            plot.setRangeAxis(rangeAxis);

            if (timeAxis.equalsIgnoreCase("utc")) {
                plot.setDataset(0, mtds);

            } else {
                plot.setDataset(0, xyds);
            }
            // Set the line thickness
            XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) plot.getRenderer();
            BasicStroke str = new BasicStroke(lineThickness);
            int n = plot.getSeriesCount();
            for (int i = 0; i < n; i++) {
                r.setSeriesStroke(i, str);
            }
            plot.setBackgroundPaint(Color.WHITE);
            // add 
            plot.setDomainGridlinesVisible(true);
            plot.setDomainGridlinePaint(Color.BLACK);
            plot.setRangeGridlinesVisible(true);
            plot.setRangeGridlinePaint(Color.BLACK);

            r.setBaseFillPaint(Color.WHITE);
            if (compact) {
                chart.removeLegend();
            }

            chart.setBackgroundPaint(Color.WHITE);

            cpnl = new ChartPanel(chart);
            imageId = saveImageAsPNG(cpnl);
        }
    } catch (LdvTableException | NoSuchAlgorithmException | SQLException | IOException ex) {
        throw new WebUtilException("Making time series plot: ", ex);
    }
    ArrayList<Integer> ret = new ArrayList<Integer>();
    ret.add(imageId);
    return ret;
}

From source file:uk.co.petertribble.jkstat.gui.KstatChart.java

private void init(List<String> statistics) {
    tsmap = new HashMap<String, TimeSeries>();
    dataset = new TimeSeriesCollection();

    // this is all the statistics
    for (String statistic : cks.getStatistics()) {
        tsmap.put(statistic, new TimeSeries(statistic));
    }/*w w w  . ja  v  a 2  s.co  m*/

    // just display these
    // FIXME what if the statistic isn't valid and isn't present in tsmap?
    for (String statistic : statistics) {
        addStatistic(statistic);
    }

    if (jkstat instanceof SequencedJKstat) {
        readAll(((SequencedJKstat) jkstat).newInstance());
    } else {
        setMaxAge(maxage);
        updateAccessory();
    }

    String ylabel = showdelta ? KstatResources.getString("CHART.RATE")
            : KstatResources.getString("CHART.VALUE");

    chart = ChartFactory.createTimeSeriesChart(cks.toString(), KstatResources.getString("CHART.TIME"), ylabel,
            dataset, true, true, false);

    setAxes();

    if (!(jkstat instanceof SequencedJKstat)) {
        startLoop();
    }
}

From source file:edu.mit.fss.examples.member.gui.PowerSubsystemPanel.java

/**
 * Instantiates a new power subsystem panel for a subsystem.
 *
 * @param subsystem the subsystem//from   w  w  w  .  j a  v  a2s.  c o m
 */
public PowerSubsystemPanel(SpacePowerSubsystem subsystem) {
    this.subsystem = subsystem;

    logger.trace("Creating and adding energy storage chart panel.");
    storageDataset = new TimeSeriesCollection();
    storageSeries = new TimeSeries("Storage");
    storageDataset.addSeries(storageSeries);
    storageChart = ChartFactory.createTimeSeriesChart(null, "Time", "Stored Energy (W-hr)", storageDataset,
            false, false, false);
    storageChart.setBackgroundPaint(getBackground());
    if (storageChart.getPlot() instanceof XYPlot) {
        XYPlot xyPlot = (XYPlot) storageChart.getPlot();
        XYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES_AND_LINES);
        renderer.setSeriesShape(0, new Ellipse2D.Double(-2, -2, 4, 4));
        xyPlot.setRenderer(renderer);
        xyPlot.setBackgroundPaint(Color.WHITE);
        xyPlot.setDomainGridlinePaint(Color.GRAY);
        xyPlot.setRangeGridlinePaint(Color.GRAY);
    }
    addTab("Storing", new ChartPanel(storageChart));

    logger.trace("Creating and adding energy transformation chart panel.");
    powerDataset = new TimeSeriesCollection();
    generationSeries = new TimeSeries("Generation");
    powerDataset.addSeries(generationSeries);
    consumptionSeries = new TimeSeries("Consumption");
    powerDataset.addSeries(consumptionSeries);
    powerChart = ChartFactory.createTimeSeriesChart(null, "Time", "Power (W)", powerDataset, true, false,
            false);
    powerChart.setBackgroundPaint(getBackground());
    if (powerChart.getPlot() instanceof XYPlot) {
        XYPlot xyPlot = (XYPlot) powerChart.getPlot();
        XYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES_AND_LINES);
        renderer.setSeriesShape(0, new Ellipse2D.Double(-2, -2, 4, 4));
        renderer.setSeriesPaint(0, Color.red);
        renderer.setSeriesShape(1, new Ellipse2D.Double(-2, -2, 4, 4));
        renderer.setSeriesPaint(1, Color.green);
        xyPlot.setRenderer(renderer);
        xyPlot.setBackgroundPaint(Color.WHITE);
        xyPlot.setDomainGridlinePaint(Color.GRAY);
        xyPlot.setRangeGridlinePaint(Color.GRAY);
    }
    JPanel chartPanel = new JPanel(new BorderLayout());
    chartPanel.add(new ChartPanel(powerChart), BorderLayout.CENTER);
    chartPanel.add(new JButton(exportAction), BorderLayout.SOUTH);
    addTab("Transforming", chartPanel);
}

From source file:org.miloss.fgsms.services.rs.impl.reports.broker.ConsumersByQueueOrTopic.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {/*from w ww  .j  ava2  s . co  m*/
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(
                "This represents the average number of consumers for all channels (topics/queues/etc) on a specific message broker.<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Channel</th><th>Average Consumer Count</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.STATISTICAL)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            try {
                data.append("<tr><td>").append(Utility.encodeHTML(urls.get(i))).append("</td>");
                double average = 0;
                try {
                    cmd = con.prepareStatement(
                            "select avg(activeconsumercount), host, canonicalname from brokerhistory where host=? and utcdatetime > ? and utcdatetime < ? group by canonicalname, host;");
                    cmd.setString(1, urls.get(i));
                    cmd.setLong(2, range.getStart().getTimeInMillis());
                    cmd.setLong(3, range.getEnd().getTimeInMillis());
                    rs = cmd.executeQuery();

                    if (rs.next()) {
                        average = rs.getDouble(1);

                    }
                } catch (Exception ex) {
                    log.log(Level.WARN, null, ex);
                } finally {
                    DBUtils.safeClose(rs);
                    DBUtils.safeClose(cmd);
                }

                data.append("<td>").append(average + "").append("</td>");

                try {
                    //ok now get the raw data....
                    cmd = con.prepareStatement(
                            "select utcdatetime,activeconsumercount, canonicalname from brokerhistory where host=? and utcdatetime > ? and utcdatetime < ?;");
                    cmd.setString(1, urls.get(i));
                    cmd.setLong(2, range.getStart().getTimeInMillis());
                    cmd.setLong(3, range.getEnd().getTimeInMillis());
                    rs = cmd.executeQuery();
                    TimeSeries ts = new TimeSeries(urls.get(i), Millisecond.class);
                    while (rs.next()) {

                        //set.addValue(rs.getLong(1), urls.get(i), rs.getString("canonicalname"));
                        GregorianCalendar gcal = new GregorianCalendar();
                        gcal.setTimeInMillis(rs.getLong(1));
                        Millisecond m = new Millisecond(gcal.getTime());

                        ts.addOrUpdate(m, rs.getLong(2));

                    }
                    col.addSeries(ts);
                } catch (Exception ex) {
                    log.log(Level.WARN, null, ex);
                } finally {
                    DBUtils.safeClose(rs);
                    DBUtils.safeClose(cmd);
                }

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            }

        }
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Count", col,
                true, false, false);

        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

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

private static XYDataset createDataset2006() {
    TimeSeries timeseries = new TimeSeries("Sales 2006");
    timeseries.add(new Month(1, 2006), 100D);
    timeseries.add(new Month(2, 2006), 102.3D);
    timeseries.add(new Month(3, 2006), 105.7D);
    timeseries.add(new Month(4, 2006), 104.2D);
    timeseries.add(new Month(5, 2006), 114.7D);
    timeseries.add(new Month(6, 2006), 121.7D);
    timeseries.add(new Month(7, 2006), 155.59999999999999D);
    timeseries.add(new Month(8, 2006), 143.19999999999999D);
    timeseries.add(new Month(9, 2006), 131.90000000000001D);
    timeseries.add(new Month(10, 2006), 120D);
    timeseries.add(new Month(11, 2006), 109.90000000000001D);
    timeseries.add(new Month(12, 2006), 99.599999999999994D);
    TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();
    timeseriescollection.addSeries(timeseries);
    timeseriescollection.setXPosition(TimePeriodAnchor.MIDDLE);
    return timeseriescollection;
}

From source file:com.sigueros.charts.LinearRegressionExample.java

/**
 * Creates a sample dataset for Linear data
 *///from  w  w w  .j  av  a 2s  .  c  om

private TimeSeriesCollection createDatasetLinear() {

    final TimeSeries linearData = new TimeSeries("Linear");

    //The Linear dataSet is the Linear Regression:
    double ad[] = Regression.getOLSRegression(getData());

    for (int i = 0; i < getData().length; i++) {
        //The formula to calculate the value is a + b * x, where a = ad[0] and b = ad [1]
        linearData.add(new Year((int) getData()[i][0]), ad[0] + ad[1] * getData()[i][0]);
    }

    TimeSeriesCollection dataLinearCollection = new TimeSeriesCollection();
    dataLinearCollection.addSeries(linearData);

    return dataLinearCollection;

}

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

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {/*  w w  w. j a va2s . c  o m*/

        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Number of status changes</th><th>Percent Uptime</th><th>Percent Downtime</th></tr>");
        DecimalFormat percentFormat = new DecimalFormat("###.#####");
        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            TimeSeries s1 = new TimeSeries(url, org.jfree.data.time.Millisecond.class);
            try {
                data.append("<tr><td>").append(url).append("</td>");
                List<StatusRecordsExt> records = getStatusRecords(urls.get(i), range, con);
                //special case, no status records available
                if (records == null || records.isEmpty()) {
                    data.append("<td>-</td><td>-</td></tr>");
                    continue;
                }
                double uptime = getUptimePercentage(records, range);
                data.append("<td>").append(records.size() + "").append("</td><td>")
                        .append(percentFormat.format(uptime)).append("</td><td>")
                        .append(percentFormat.format(100 - uptime)).append("</td></tr>");
                TimeSeriesDataItem t = null;
                for (int k = 0; k < records.size(); k++) {
                    if (records.get(k).status) {
                        try {
                            t = new TimeSeriesDataItem(new Millisecond(records.get(k).gcal.getTime()), 1);
                            s1.addOrUpdate(t);
                        } catch (Exception ex) {
                            log.log(Level.WARN, null, ex);
                        }
                    } else {
                        try {
                            t = new TimeSeriesDataItem(new Millisecond(records.get(k).gcal.getTime()), 0);
                            s1.addOrUpdate(t);
                        } catch (Exception ex) {
                            log.log(Level.WARN, null, ex);
                        }
                    }
                    col.addSeries(s1);
                }

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            }

        }
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Status", col,
                true, false, false);

        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 800);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");

        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:Views.GraphView.java

public GraphView(RegularTimePeriod T, String title, double openPrice) {
    graphTitle = title;/*w  w w. j  a  v  a  2 s.co m*/

    lastValueAsk = openPrice;
    lastValueBid = openPrice;
    lastValueExecuted = openPrice;

    newValueAsk = openPrice;
    newValueBid = openPrice;
    lastexectuednew = openPrice;

    this.BidValuePlot = new TimeSeries("Bid", Millisecond.class);
    this.AskValuePlot = new TimeSeries("Ask", Millisecond.class);
    this.VolumeBidPlot = new TimeSeries("Volume Bid", Millisecond.class);
    this.VolumeAskPlot = new TimeSeries("Volume Ask", Millisecond.class);
    this.ExecutedValuePlot = new TimeSeries("Last Executed", Millisecond.class);
    this.VolumeExecPlot = new TimeSeries("Volume Last Executed", Millisecond.class);

    this.Tdebut = T;
    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(BidValuePlot);
    dataset.addSeries(AskValuePlot);
    this.BidValuePlot.add(Tdebut, lastValueBid);
    this.AskValuePlot.add(Tdebut, lastValueAsk);
    dataset2 = new TimeSeriesCollection();
    dataset2.addSeries(VolumeBidPlot);
    dataset2.addSeries(VolumeAskPlot);
    this.VolumeBidPlot.add(Tdebut, lastVolumeBid);
    this.VolumeAskPlot.add(Tdebut, lastVolumeAsk);

    dataset3 = new TimeSeriesCollection();
    dataset3.addSeries(ExecutedValuePlot);
    dataset4 = new TimeSeriesCollection();

    dataset4.addSeries(VolumeExecPlot);
    chart = createChart(dataset);

    //Sets background color of chart
    chart.setBackgroundPaint(Color.LIGHT_GRAY);
    chartPanel = new ChartPanel(chart);

    timer = new Timer(0, this);
    timer.start();

}