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

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

Introduction

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

Prototype

public TimeSeries(Comparable name, Class timePeriodClass) 

Source Link

Document

Creates a new (empty) time series with the specified name and class of RegularTimePeriod .

Usage

From source file:org.posterita.core.TimeSeriesChart.java

/**
 * Takes a sql as input and generates a Timeseries that is added to
 * the dataset.    //w w w .  j ava2  s  .  co m
 * Note: The sql must return 3 columns only Series, date & value
 * Column 1: Type -> String
 * Column 2: Type -> String or Date. For String the format must be as dd-MM-yyyy
 * Column 3: Type -> BigDecimal
 * 
 * @param sql
 */
public void getDataSetFromSQL(String sql) throws OperationException {
    PreparedStatement pstmt = DB.prepareStatement(sql, null);

    ArrayList<Object[]> dataSource = ReportManager.getReportData(pstmt);
    int count = 0;

    String seriesName = null;
    TimeSeries series = null;
    BigDecimal value = null;
    int day = 0;
    int month = 0;
    int year = 0;

    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();

    for (Object[] data : dataSource) {
        if (data.length != 3)
            throw new OperationException(
                    "Unable to generate timeseries. Cause:Invalid sql, the return resultset must have 3 columns only");

        count++;
        if (count == 1) {
            continue;
        }

        seriesName = (String) data[0];
        String date = (String) data[1];
        value = (BigDecimal) data[2];
        String s[] = date.split("-");

        if (s.length != 3)
            throw new OperationException("Unable to generate timeseries. "
                    + "Cause:Invalid date format, the date returned should have the following format 'DD-MM-YYYY'");

        SimpleDateFormat sdf = new SimpleDateFormat();
        Calendar cal = Calendar.getInstance();
        Date d = null;

        try {
            sdf.applyPattern("DD-MM-YYYY");
            d = sdf.parse(date);
        } catch (ParseException e1) {
            try {
                sdf.applyPattern("DD-MMM-YYYY");
                d = sdf.parse(date);
            } catch (ParseException e) {
                throw new OperationException("Unable to generate timeseries. "
                        + "Cause:Invalid date format, the date returned should have one of the following formats 'DD-MM-YYYY' or 'DD-MMM-YYYY'",
                        e);
            }
        }

        cal.setTime(d);

        day = cal.get(Calendar.DATE);
        month = cal.get(Calendar.MONTH) + 1;
        year = cal.get(Calendar.YEAR);

        series = timeSeriesCollection.getSeries(seriesName);

        if (series == null) {
            series = new TimeSeries(seriesName, Day.class);
            series.add(new Day(day, month, year), value);

            timeSeriesCollection.addSeries(series);
        } else {
            series.add(new Day(day, month, year), value);
        } //if   

    } //for

    dataset = timeSeriesCollection;
}

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

/**
 * Creates a dataset containing random values at weekly intervals.
 *
 * @param items  the number of items in the dataset.
 * /*  w w w .  ja va2 s  . c  o  m*/
 * @return the dataset.
 */
private XYDataset createDataset(final int items) {

    final TimeSeries s1 = new TimeSeries("Random Data", Week.class);
    RegularTimePeriod t = new Week();
    double v = 100.0;
    for (int i = 0; i < items; i++) {
        s1.add(t, v);
        v = v * (1 + ((Math.random() - 0.499) / 100.0));
        t = t.next();
    }

    final TimeSeriesCollection dataset = new TimeSeriesCollection(s1);
    dataset.setDomainIsPointsInTime(true);

    return dataset;

}

From source file:org.infoglue.deliver.util.charts.TimeSeriesDiagram.java

/**
 * Creates a dataset, consisting of two series of monthly data.
 *
 * @return the dataset.//from  w  w  w . j  av  a2s.  c  om
 */
private XYDataset createDataset() throws Exception {
    TimeSeriesCollection timeSeriesDataset = new TimeSeriesCollection();

    Document document = new DOMBuilder().getDocument(this.xmlData);
    this.writeDebug(document);

    Element headerElement = (Element) document.selectSingleNode("//chartHeader");
    this.header = headerElement.getText();
    Element axisYHeaderElement = (Element) document.selectSingleNode("//axisYHeader");
    this.axisYHeader = axisYHeaderElement.getText();
    Element axisXHeaderElement = (Element) document.selectSingleNode("//axisXHeader");
    this.axisXHeader = axisXHeaderElement.getText();
    Element timeGranularityElement = (Element) document.selectSingleNode("//timeGranularity");
    this.timeGranulariry = timeGranularityElement.getText();
    Element dateFormatElement = (Element) document.selectSingleNode("//dateFormat");
    this.dateFormat = dateFormatElement.getText();

    List series = document.selectNodes("//Series");

    Iterator seriesIterator = series.iterator();
    while (seriesIterator.hasNext()) {
        Element serieElement = (Element) seriesIterator.next();
        String serieName = serieElement.attributeValue("name");

        TimeSeries s1 = null;
        if (this.timeGranulariry.equalsIgnoreCase("Month"))
            s1 = new TimeSeries(serieName, Month.class);
        else if (this.timeGranulariry.equalsIgnoreCase("Week"))
            s1 = new TimeSeries(serieName, Week.class);

        List items = serieElement.selectNodes("Item");
        Iterator itemsIterator = items.iterator();
        while (itemsIterator.hasNext()) {
            Element itemElement = (Element) itemsIterator.next();
            Element yearElement = (Element) itemElement.selectSingleNode("yearId");
            Element timeElement = (Element) itemElement.selectSingleNode("timeId");
            Element valueElement = (Element) itemElement.selectSingleNode("value");
            String year = yearElement.getText();
            String time = timeElement.getText();
            String value = valueElement.getText();

            if (this.timeGranulariry.equalsIgnoreCase("Month"))
                s1.add(new Month(new Integer(time).intValue(), new Integer(year).intValue()), new Float(value));
            else if (this.timeGranulariry.equalsIgnoreCase("Week"))
                s1.add(new Week(new Integer(time).intValue(), new Integer(year).intValue()), new Float(value));
        }

        timeSeriesDataset.addSeries(s1);
        //timeSeriesDataset.addSeries(s2);

        timeSeriesDataset.setDomainIsPointsInTime(true);

    }

    return timeSeriesDataset;

}

From source file:eu.hydrologis.jgrass.charting.impl.JGrassXYTimeLineChart.java

public JGrassXYTimeLineChart(String[] chartTitles, double[][][] chartValues, Class<?> timeClass) {
    try {/*from   w w  w .ja  v a  2s  .  com*/
        chartSeries = new TimeSeries[chartValues.length];

        constructor = (Constructor<RegularTimePeriod>) timeClass.getConstructor(Date.class);

        for (int i = 0; i < chartTitles.length; i++) {
            final String title = chartTitles[i];
            final double[][] values = chartValues[i];

            chartSeries[i] = new TimeSeries(title, timeClass);
            for (int j = 0; j < values[0].length; j++) {
                // important: the data matrix has to be passed as two rows (not
                // two columns)
                if (values[0][j] == 0)
                    break;
                double val = values[1][j];
                if (isNovalue(val) || isNovalue(values[0][j]))
                    continue;
                chartSeries[i].add(constructor.newInstance(new Date((long) values[0][j])), val);
            }
        }

        lineDataset = new TimeSeriesCollection();
        for (int i = 0; i < chartSeries.length; i++) {
            lineDataset.addSeries(chartSeries[i]);
        }
        lineDataset.setXPosition(TimePeriodAnchor.MIDDLE);
        lineDataset.setDomainIsPointsInTime(true);

    } catch (Exception e) {
        ChartPlugin.log("ChartPlugin problem", e); //$NON-NLS-1$
    }

}

From source file:OverlaidXYPlotDemo2.java

/**
 * Creates a sample dataset./*w  w  w.  j  av a2  s.c  o m*/
 *
 * @return The dataset.
 */
private IntervalXYDataset createDataset1() {

    // create dataset 1...
    final TimeSeries series1 = new TimeSeries("Series 1", Day.class);
    series1.add(new Day(1, SerialDate.MARCH, 2002), 12353.3);
    series1.add(new Day(2, SerialDate.MARCH, 2002), 13734.4);
    series1.add(new Day(3, SerialDate.MARCH, 2002), 14525.3);
    series1.add(new Day(4, SerialDate.MARCH, 2002), 13984.3);
    series1.add(new Day(5, SerialDate.MARCH, 2002), 12999.4);
    series1.add(new Day(6, SerialDate.MARCH, 2002), 14274.3);
    series1.add(new Day(7, SerialDate.MARCH, 2002), 15943.5);
    series1.add(new Day(8, SerialDate.MARCH, 2002), 14845.3);
    series1.add(new Day(9, SerialDate.MARCH, 2002), 14645.4);
    series1.add(new Day(10, SerialDate.MARCH, 2002), 16234.6);
    series1.add(new Day(11, SerialDate.MARCH, 2002), 17232.3);
    series1.add(new Day(12, SerialDate.MARCH, 2002), 14232.2);
    series1.add(new Day(13, SerialDate.MARCH, 2002), 13102.2);
    series1.add(new Day(14, SerialDate.MARCH, 2002), 14230.2);
    series1.add(new Day(15, SerialDate.MARCH, 2002), 11235.2);

    final TimeSeriesCollection result = new TimeSeriesCollection(series1);
    return result;

}

From source file:edu.unibonn.plotting.TimeSeriesPlotter_Sensors.java

private XYDataset createDataset(ArrayList<Sensor> sensors) {
    final TimeSeriesCollection dataset = new TimeSeriesCollection();

    for (int i = 0; i < sensors.size(); i++) {
        Sensor current_sensor = sensors.get(i);

        final TimeSeries s1 = new TimeSeries("Sensor " + i, Hour.class);

        for (int j = 0; j < current_sensor.getDimensions(); j++) {
            LocalDateTime current_record_time = current_sensor.getInitial_record_time().plusHours(j);
            s1.add(new Hour(current_record_time.getHour(), current_record_time.getDayOfMonth(),
                    current_record_time.getMonthValue(), current_record_time.getYear()),
                    current_sensor.getMeasurement(j));
        }/* w w  w .jav  a  2 s  .c o m*/

        dataset.addSeries(s1);
    }

    dataset.setDomainIsPointsInTime(true);

    return dataset;
}

From source file:eu.hydrologis.jgrass.charting.impl.JGrassXYTimeBarChart.java

public JGrassXYTimeBarChart(String[] chartTitles, double[][][] chartValues, Class<?> timeClass,
        double barWidth) {
    try {// w ww .  j  a  va  2 s  .c o  m
        chartSeries = new TimeSeries[chartValues.length];

        constructor = (Constructor<RegularTimePeriod>) timeClass.getConstructor(Date.class);

        for (int i = 0; i < chartTitles.length; i++) {
            final String title = chartTitles[i];
            final double[][] values = chartValues[i];

            chartSeries[i] = new TimeSeries(title, timeClass);
            for (int j = 0; j < values[0].length; j++) {
                // important: the data matrix has to be passed as two rows (not
                // two columns)
                double val = values[1][j];
                if (isNovalue(val))
                    continue;
                chartSeries[i].add(constructor.newInstance(new Date((long) values[0][j])), val);
            }
        }

        lineDataset = new TimeSeriesCollection();
        for (int i = 0; i < chartSeries.length; i++) {
            lineDataset.addSeries(chartSeries[i]);
        }
        lineDataset.setXPosition(TimePeriodAnchor.MIDDLE);
        lineDataset.setDomainIsPointsInTime(true);

        if (barWidth != -1)
            dataset = new XYBarDataset(lineDataset, barWidth);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

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

/**
 * Creates a sample dataset./*from w  w  w .  ja  v  a2 s. c om*/
 * 
 * @param name  the dataset name.
 * @param base  the starting value.
 * @param start  the starting period.
 * @param count  the number of values to generate.
 *
 * @return The dataset.
 */
private XYDataset createDataset(final String name, final double base, final RegularTimePeriod start,
        final int count) {

    final TimeSeries series = new TimeSeries(name, start.getClass());
    RegularTimePeriod period = start;
    double value = base;
    for (int i = 0; i < count; i++) {
        series.add(period, value);
        period = period.previous();
        value = value * (1 + (Math.random() - 0.495) / 10.0);
    }

    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);

    return dataset;

}

From source file:com.android.ddmuilib.log.event.DisplayGraph.java

/**
* Updates the chart with the {@link EventContainer} by adding the values/occurrences defined
* by the {@link ValueDisplayDescriptor} and {@link OccurrenceDisplayDescriptor} objects from
* the two lists./*  w  ww .j  av  a  2 s . c o m*/
* <p/>This method is only called when at least one of the descriptor list is non empty.
* @param event
* @param logParser
* @param valueDescriptors
* @param occurrenceDescriptors
*/
private void updateChart(EventContainer event, EventLogParser logParser,
        ArrayList<ValueDisplayDescriptor> valueDescriptors,
        ArrayList<OccurrenceDisplayDescriptor> occurrenceDescriptors) {
    Map<Integer, String> tagMap = logParser.getTagMap();

    Millisecond millisecondTime = null;
    long msec = -1;

    // If the event container is a cpu container (tag == 2721), and there is no descriptor
    // for the total CPU load, then we do accumulate all the values.
    boolean accumulateValues = false;
    double accumulatedValue = 0;

    if (event.mTag == 2721) {
        accumulateValues = true;
        for (ValueDisplayDescriptor descriptor : valueDescriptors) {
            accumulateValues &= (descriptor.valueIndex != 0);
        }
    }

    for (ValueDisplayDescriptor descriptor : valueDescriptors) {
        try {
            // get the hashmap for this descriptor
            HashMap<Integer, TimeSeries> map = mValueDescriptorSeriesMap.get(descriptor);

            // if it's not there yet, we create it.
            if (map == null) {
                map = new HashMap<Integer, TimeSeries>();
                mValueDescriptorSeriesMap.put(descriptor, map);
            }

            // get the TimeSeries for this pid
            TimeSeries timeSeries = map.get(event.pid);

            // if it doesn't exist yet, we create it
            if (timeSeries == null) {
                // get the series name
                String seriesFullName = null;
                String seriesLabel = getSeriesLabel(event, descriptor);

                switch (mValueDescriptorCheck) {
                case EVENT_CHECK_SAME_TAG:
                    seriesFullName = String.format("%1$s / %2$s", seriesLabel, descriptor.valueName);
                    break;
                case EVENT_CHECK_SAME_VALUE:
                    seriesFullName = String.format("%1$s", seriesLabel);
                    break;
                default:
                    seriesFullName = String.format("%1$s / %2$s: %3$s", seriesLabel,
                            tagMap.get(descriptor.eventTag), descriptor.valueName);
                    break;
                }

                // get the data set for this ValueType
                TimeSeriesCollection dataset = getValueDataset(
                        logParser.getEventInfoMap().get(event.mTag)[descriptor.valueIndex].getValueType(),
                        accumulateValues);

                // create the series
                timeSeries = new TimeSeries(seriesFullName, Millisecond.class);
                if (mMaximumChartItemAge != -1) {
                    timeSeries.setMaximumItemAge(mMaximumChartItemAge * 1000);
                }

                dataset.addSeries(timeSeries);

                // add it to the map.
                map.put(event.pid, timeSeries);
            }

            // update the timeSeries.

            // get the value from the event
            double value = event.getValueAsDouble(descriptor.valueIndex);

            // accumulate the values if needed.
            if (accumulateValues) {
                accumulatedValue += value;
                value = accumulatedValue;
            }

            // get the time
            if (millisecondTime == null) {
                msec = (long) event.sec * 1000L + (event.nsec / 1000000L);
                millisecondTime = new Millisecond(new Date(msec));
            }

            // add the value to the time series
            timeSeries.addOrUpdate(millisecondTime, value);
        } catch (InvalidTypeException e) {
            // just ignore this descriptor if there's a type mismatch
        }
    }

    for (OccurrenceDisplayDescriptor descriptor : occurrenceDescriptors) {
        try {
            // get the hashmap for this descriptor
            HashMap<Integer, TimeSeries> map = mOcurrenceDescriptorSeriesMap.get(descriptor);

            // if it's not there yet, we create it.
            if (map == null) {
                map = new HashMap<Integer, TimeSeries>();
                mOcurrenceDescriptorSeriesMap.put(descriptor, map);
            }

            // get the TimeSeries for this pid
            TimeSeries timeSeries = map.get(event.pid);

            // if it doesn't exist yet, we create it.
            if (timeSeries == null) {
                String seriesLabel = getSeriesLabel(event, descriptor);

                String seriesFullName = String.format("[%1$s:%2$s]", tagMap.get(descriptor.eventTag),
                        seriesLabel);

                timeSeries = new TimeSeries(seriesFullName, Millisecond.class);
                if (mMaximumChartItemAge != -1) {
                    timeSeries.setMaximumItemAge(mMaximumChartItemAge);
                }

                getOccurrenceDataSet().addSeries(timeSeries);

                map.put(event.pid, timeSeries);
            }

            // update the series

            // get the time
            if (millisecondTime == null) {
                msec = (long) event.sec * 1000L + (event.nsec / 1000000L);
                millisecondTime = new Millisecond(new Date(msec));
            }

            // add the value to the time series
            timeSeries.addOrUpdate(millisecondTime, 0); // the value is unused
        } catch (InvalidTypeException e) {
            // just ignore this descriptor if there's a type mismatch
        }
    }

    // go through all the series and remove old values.
    if (msec != -1 && mMaximumChartItemAge != -1) {
        Collection<HashMap<Integer, TimeSeries>> pidMapValues = mValueDescriptorSeriesMap.values();

        for (HashMap<Integer, TimeSeries> pidMapValue : pidMapValues) {
            Collection<TimeSeries> seriesCollection = pidMapValue.values();

            for (TimeSeries timeSeries : seriesCollection) {
                timeSeries.removeAgedItems(msec, true);
            }
        }

        pidMapValues = mOcurrenceDescriptorSeriesMap.values();
        for (HashMap<Integer, TimeSeries> pidMapValue : pidMapValues) {
            Collection<TimeSeries> seriesCollection = pidMapValue.values();

            for (TimeSeries timeSeries : seriesCollection) {
                timeSeries.removeAgedItems(msec, true);
            }
        }
    }
}

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

/**
 * Another test of the clone() method.//from w ww. j a va  2 s .  c  o m
 */
@Test
public void testClone2() throws CloneNotSupportedException {
    TimeSeries s1 = new TimeSeries("S1", Year.class);
    s1.add(new Year(2007), 100.0);
    s1.add(new Year(2008), null);
    s1.add(new Year(2009), 200.0);
    TimeSeries s2 = (TimeSeries) s1.clone();
    assertTrue(s1.equals(s2));

    // check independence
    s2.addOrUpdate(new Year(2009), 300.0);
    assertFalse(s1.equals(s2));
    s1.addOrUpdate(new Year(2009), 300.0);
    assertTrue(s1.equals(s2));
}