Example usage for org.jfree.data.time TimeSeries getTimePeriod

List of usage examples for org.jfree.data.time TimeSeries getTimePeriod

Introduction

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

Prototype

public RegularTimePeriod getTimePeriod(int index) 

Source Link

Document

Returns the time period at the specified index.

Usage

From source file:com.bpd.jfreechart.StackedAreaChartDemo.java

/**
 * Test program that will display a JFreeChart showing interpolated data points.
 * /*from   ww  w .  j  av  a 2 s  .co  m*/
 * @param args <b>"1"</b> to display Series 1. <b>"2"</b> to display Series 2. <b>"0"</b> to
 * display both series.
 */
public static void main(String... args) {
    // Check arguments.
    if (args.length != 1) {
        System.err.println("Usage: java Chart [0|1|2]\n\n  -- 0: Display Series 1.");
        System.err.println("  -- 1: Display Series 2.\n  -- 2: Display both series.");
        return;
    }

    String option = args[0];
    if (!"0".equals(option) && !"1".equals(option) && !"2".equals(option)) {
        System.err.println("Invalid argument: " + option);
        return;
    }

    // Create some sample data.
    List<Point<Number, Number>> list1 = new ArrayList<Point<Number, Number>>();
    list1.add(new Point<Number, Number>(50, 100.0));
    list1.add(new Point<Number, Number>(150, 100));
    list1.add(new Point<Number, Number>(250, 200));
    list1.add(new Point<Number, Number>(350, 400));
    list1.add(new Point<Number, Number>(450, 200));
    list1.add(new Point<Number, Number>(550, 100));

    List<Point<Number, Number>> list2 = new ArrayList<Point<Number, Number>>();
    list2.add(new Point<Number, Number>(50, 100.0));
    list2.add(new Point<Number, Number>(150, 200.0));
    list2.add(new Point<Number, Number>(250, 400.0));
    list2.add(new Point<Number, Number>(350, 600.0));
    list2.add(new Point<Number, Number>(450, 400.0));
    list2.add(new Point<Number, Number>(550, 200.0));

    // Add data to time series.
    TimeSeries series1 = new TimeSeries("Series 1", FixedMillisecond.class);
    for (Point<Number, Number> dataPoint : list1) {
        if ("1".equals(option) || "0".equals(option)) {
            series1.add(new FixedMillisecond(dataPoint.getX().longValue()), dataPoint.getY());
        }
        series1.setDescription("Series 1");
    }

    TimeSeries series2 = new TimeSeries("Series 2", FixedMillisecond.class);
    for (Point<Number, Number> dataPoint : list2) {
        if ("2".equals(option) || "0".equals(option)) {
            series2.add(new FixedMillisecond(dataPoint.getX().longValue()), dataPoint.getY());
        }
        series2.setDescription("Series 2");
    }

    TimeSeriesCollection collection = new TimeSeriesCollection();
    if ("1".equals(option)) {
        collection.addSeries(series1);
    } else if ("2".equals(option)) {
        collection.addSeries(series2);
    } else if ("0".equals(option)) {
        collection.addSeries(series1);
        collection.addSeries(series2);
    }

    TimeTableXYDataset dataset = new TimeTableXYDataset();
    @SuppressWarnings("unchecked")
    List<TimeSeries> timeSeriesList = collection.getSeries();
    for (TimeSeries t : timeSeriesList) {
        for (int index = 0; index < t.getItemCount(); index++) {
            TimeSeriesDataItem dataItem = (TimeSeriesDataItem) t.getItems().get(index);
            dataset.add(t.getTimePeriod(index), dataItem.getValue().doubleValue(), t.getDescription());
        }
    }

    // Create and display chart.
    JFreeChart chart = ChartFactory.createStackedXYAreaChart(null, null, null, dataset,
            PlotOrientation.VERTICAL, false, true, false);

    customizeChart(chart);

    ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));

    JFrame frame = new JFrame();
    frame.getContentPane().add(chartPanel);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

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

/**
 * Create a XYZ dataset from a time series with Y.
 *
 * @param source// ww w . j av a 2  s .  c  o  m
 * @return
 */
public static final XYZDataset createXYZTimeSeries(final TimeSeries source) {

    final RegularTimePeriod lastTimePeriod = source.getTimePeriod(source.getItemCount() - 1);
    // process all timeperiods including empty ones
    RegularTimePeriod t = source.getTimePeriod(0);
    final List<Double> zValuesList = new LinkedList<>();
    while (!(t.getFirstMillisecond() > lastTimePeriod.getFirstMillisecond())) {
        zValuesList.add(getValue(source, t));
        t = t.next();
    }
    final double[] xValues = new double[zValuesList.size()];
    final double[] yValues = new double[zValuesList.size()];
    final double[] zValues = new double[zValuesList.size()];
    t = source.getTimePeriod(0);
    for (int i = 0; i < zValuesList.size(); i++) {
        xValues[i] = t.getFirstMillisecond();
        yValues[i] = 0;
        zValues[i] = zValuesList.get(i);
        t = t.next();
    }
    final DefaultXYZDataset target = new DefaultXYZDataset();
    target.addSeries(0, new double[][] { xValues, yValues, zValues });

    return target;
}

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

/**
 * Create a moving average time series from a given source series.
 *
 * @param source the source timeseries/*from w  ww  . j av a 2  s  .  com*/
 * @param preLen number of timeperiods before current time period included in
 * moving average calculation
 * @param postLen number of timeperiods after current time period included in
 * moving average calculation
 * @return a moving average time series
 */
public static TimeSeries createMovingAverage(final TimeSeries source, final int preLen, final int postLen) {

    final int len = preLen + postLen + 1;
    final TimeSeries result = new TimeSeries(source.getKey());
    final RegularTimePeriod lastTimePeriod = source.getTimePeriod(source.getItemCount() - 1);

    // process all timeperiods including empty ones
    RegularTimePeriod t = source.getTimePeriod(0);
    while (!(t.getFirstMillisecond() > lastTimePeriod.getFirstMillisecond())) {

        // calculate the moving avg value for the current time period
        double value = getValue(source, t);
        RegularTimePeriod ti = t;
        for (int i = 0; i < preLen; i++) {
            ti = ti.previous();
            value += getValue(source, ti);
        }
        ti = t;
        for (int i = 0; i < postLen; i++) {
            ti = ti.next();
            value += getValue(source, ti);
        }

        // add the moving avg value to the included time periods
        result.addOrUpdate(t, value / len);
        t = t.next();
    }

    return result;
}

From source file:org.jfree.data.time.MovingAverage.java

/**
 * Creates a new {@link TimeSeries} containing moving average values for
 * the given series.  If the series is empty (contains zero items), the
 * result is an empty series./*from w w  w . j  a v a 2s.  c om*/
 *
 * @param source  the source series.
 * @param name  the name of the new series.
 * @param periodCount  the number of periods used in the average
 *                     calculation.
 * @param skip  the number of initial periods to skip.
 *
 * @return The moving average series.
 */
public static TimeSeries createMovingAverage(TimeSeries source, String name, int periodCount, int skip) {

    ParamChecks.nullNotPermitted(source, "source");
    if (periodCount < 1) {
        throw new IllegalArgumentException("periodCount must be greater " + "than or equal to 1.");
    }

    TimeSeries result = new TimeSeries(name);

    if (source.getItemCount() > 0) {

        // if the initial averaging period is to be excluded, then
        // calculate the index of the
        // first data item to have an average calculated...
        long firstSerial = source.getTimePeriod(0).getSerialIndex() + skip;

        for (int i = source.getItemCount() - 1; i >= 0; i--) {

            // get the current data item...
            RegularTimePeriod period = source.getTimePeriod(i);
            long serial = period.getSerialIndex();

            if (serial >= firstSerial) {
                // work out the average for the earlier values...
                int n = 0;
                double sum = 0.0;
                long serialLimit = period.getSerialIndex() - periodCount;
                int offset = 0;
                boolean finished = false;

                while ((offset < periodCount) && (!finished)) {
                    if ((i - offset) >= 0) {
                        TimeSeriesDataItem item = source.getRawDataItem(i - offset);
                        RegularTimePeriod p = item.getPeriod();
                        Number v = item.getValue();
                        long currentIndex = p.getSerialIndex();
                        if (currentIndex > serialLimit) {
                            if (v != null) {
                                sum = sum + v.doubleValue();
                                n = n + 1;
                            }
                        } else {
                            finished = true;
                        }
                    }
                    offset = offset + 1;
                }
                if (n > 0) {
                    result.add(period, sum / n);
                } else {
                    result.add(period, null);
                }
            }

        }
    }

    return result;

}

From source file:net.sf.jasperreports.charts.util.TimeSeriesChartHyperlinkProvider.java

@Override
public JRPrintHyperlink getEntityHyperlink(ChartEntity entity) {
    JRPrintHyperlink printHyperlink = null;
    if (hasHyperlinks() && entity instanceof XYItemEntity) {
        XYItemEntity itemEntity = (XYItemEntity) entity;
        TimeSeriesCollection dataset = (TimeSeriesCollection) itemEntity.getDataset();
        TimeSeries series = dataset.getSeries(itemEntity.getSeriesIndex());
        Map<RegularTimePeriod, JRPrintHyperlink> serieHyperlinks = itemHyperlinks.get(series.getKey());
        if (serieHyperlinks != null) {
            RegularTimePeriod timePeriod = series.getTimePeriod(itemEntity.getItem());
            printHyperlink = serieHyperlinks.get(timePeriod);
        }//from  w  w  w. j av a2s . c  o  m
    }
    return printHyperlink;
}

From source file:com.haskins.cloudtrailviewer.feature.MetricsFeature.java

@Override
public void chartMouseClicked(ChartMouseEvent cme) {

    try {//from  www.j a  v a2 s. c  o  m
        XYItemEntity xyitem = (XYItemEntity) cme.getEntity();
        TimeSeriesCollection dataset = (TimeSeriesCollection) xyitem.getDataset();
        List<TimeSeries> series = dataset.getSeries();
        TimeSeries timeSeries = series.get(xyitem.getSeriesIndex());
        Second second = (Second) timeSeries.getTimePeriod(xyitem.getItem());

        if (!eventTable.isVisible()) {

            jsp.setDividerLocation(0.5);
            jsp.setDividerSize(3);
            eventTable.setVisible(true);
        }

        eventTable.clearEvents();
        eventTable.setEvents(secondEvents.get(second));

    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Problem responding to Chart click event", e);
    }
}

From source file:org.amanzi.awe.charts.ui.ChartsView.java

@Override
public void chartMouseClicked(final ChartMouseEvent event) {
    if (event == null) {
        return;/* w  w  w .jav a2 s .  c o  m*/
    }
    Collection<String> groups = null;
    long startDate = Long.MIN_VALUE;
    long endDate = Long.MAX_VALUE;
    String cellName = StringUtils.EMPTY;

    if (event.getEntity() instanceof CategoryItemEntity) {
        CategoryItemEntity entity = (CategoryItemEntity) event.getEntity();
        IColumn period = (IColumn) entity.getColumnKey();
        ICategoryRow column = period.getItemByName((String) entity.getRowKey());

        groups = column.getGroupsNames();
        startDate = period.getStartDate();
        endDate = period.getEndDate();
        cellName = column.getName();
    } else if (event.getEntity() instanceof XYItemEntity) {
        XYItemEntity entity = (XYItemEntity) event.getEntity();
        TimeSeriesCollection dataset = (TimeSeriesCollection) entity.getDataset();
        TimeSeries ts = dataset.getSeries(entity.getSeriesIndex());
        ITimeRow row = (ITimeRow) ts.getKey();
        RegularTimePeriod period = ts.getTimePeriod(entity.getItem());

        startDate = period.getStart().getTime();
        endDate = container.getPeriod().addPeriod(startDate);
        groups = row.getGroupsForTime(startDate);
        cellName = row.getName();
    } else {
        return;
    }

    AWEEventManager.getManager().fireShowInViewEvent(model,
            new StatisticsFilter(container.getPeriod(), startDate, endDate, groups, cellName), this);
}

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

/**
 * Exports this panel's connectivity dataset.
 *///from   w  w  w.j  av a  2 s .  com
private void exportDataset() {
    if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(this)) {
        File f = fileChooser.getSelectedFile();

        if (!f.exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
                "Overwrite existing file " + f.getName() + "?", "File Exists", JOptionPane.YES_NO_OPTION)) {
            logger.info("Exporting dataset to file " + f.getPath() + ".");
            try {
                BufferedWriter bw = Files.newBufferedWriter(Paths.get(f.getPath()), Charset.defaultCharset());

                StringBuilder b = new StringBuilder();

                // synchronize on map for thread safety
                synchronized (connectSeriesMap) {
                    for (Transmitter tx : connectSeriesMap.keySet()) {
                        TimeSeries s = connectSeriesMap.get(tx);
                        b.append(tx.getName()).append(" Connectivity\n").append("Time, Value\n");
                        for (int j = 0; j < s.getItemCount(); j++) {
                            b.append(s.getTimePeriod(j).getStart().getTime()).append(", ").append(s.getValue(j))
                                    .append("\n");
                        }
                    }
                }

                bw.write(b.toString());
                bw.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.targetcharts.SparkLine.java

private void addPointSeries(TimeSeries series, XYPlot plot) {
    logger.debug("IN");
    TimeSeries pointSerie = new TimeSeries("Point", Month.class);
    for (int i = 0; i < series.getItemCount(); i++) {
        pointSerie.add(series.getTimePeriod(i), series.getValue(i));
    }/* www  . j  a  v a  2 s. c  o m*/
    final TimeSeriesCollection avgDs = new TimeSeriesCollection(pointSerie);

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false) {
        public boolean getItemShapeVisible(int _series, int item) {
            return (true);
        }
    };
    renderer.setSeriesPaint(2, Color.LIGHT_GRAY);
    renderer.setBaseShapesVisible(true);
    renderer.setBaseShapesFilled(true);
    renderer.setDrawOutlines(true);
    renderer.setUseFillPaint(true);
    renderer.setBaseFillPaint(Color.BLACK);
    renderer.setBaseOutlinePaint(Color.BLACK);
    renderer.setUseOutlinePaint(true);
    renderer.setSeriesShape(0, new Ellipse2D.Double(-2.0, -2.0, 4.0, 4.0));

    plot.setDataset(2, avgDs);
    plot.setRenderer(2, renderer);
    logger.debug("OUT");

}

From source file:utilesChart.util.TimeSeriesCollection.java

/**
 * Returns the starting X value for the specified series and item.
 *
 * @param series  the series (zero-based index).
 * @param item  the item (zero-based index).
 *
 * @return The value./*  ww w .  j  av a2  s  .c o  m*/
 */
public synchronized Number getStartX(int series, int item) {
    TimeSeries ts = (TimeSeries) this.data.get(series);
    return new Long(ts.getTimePeriod(item).getFirstMillisecond(this.workingCalendar));
}