List of usage examples for org.jfree.data.time TimeSeriesDataItem getValue
public Number getValue()
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 . c o 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: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 ww . j av a2 s . 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:org.jfree.data.time.MovingAverage.java
/** * Creates a new {@link TimeSeries} containing moving average values for * the given series, calculated by number of points (irrespective of the * 'age' of those points). If the series is empty (contains zero items), * the result is an empty series./* w w w.j av a 2 s. c om*/ * <p> * Developed by Benoit Xhenseval (www.ObjectLab.co.uk). * * @param source the source series. * @param name the name of the new series. * @param pointCount the number of POINTS used in the average calculation * (not periods!) * * @return The moving average series. */ public static TimeSeries createPointMovingAverage(TimeSeries source, String name, int pointCount) { ParamChecks.nullNotPermitted(source, "source"); if (pointCount < 2) { throw new IllegalArgumentException("periodCount must be greater " + "than or equal to 2."); } TimeSeries result = new TimeSeries(name); double rollingSumForPeriod = 0.0; for (int i = 0; i < source.getItemCount(); i++) { // get the current data item... TimeSeriesDataItem current = source.getRawDataItem(i); RegularTimePeriod period = current.getPeriod(); // FIXME: what if value is null on next line? rollingSumForPeriod += current.getValue().doubleValue(); if (i > pointCount - 1) { // remove the point i-periodCount out of the rolling sum. TimeSeriesDataItem startOfMovingAvg = source.getRawDataItem(i - pointCount); rollingSumForPeriod -= startOfMovingAvg.getValue().doubleValue(); result.add(period, rollingSumForPeriod / pointCount); } else if (i == pointCount - 1) { result.add(period, rollingSumForPeriod / pointCount); } } return result; }
From source file:edu.fullerton.viewerplugin.PluginSupport.java
public static int scaleRange(TimeSeriesCollection mtds, Double miny, Double maxy) { int exp = PluginSupport.getExp(miny, maxy); double scale = Math.pow(10, exp); for (Iterator it = mtds.getSeries().iterator(); it.hasNext();) { TimeSeries ds = (TimeSeries) it.next(); for (int item = 0; item < ds.getItemCount(); item++) { TimeSeriesDataItem dataItem = ds.getDataItem(item); RegularTimePeriod period = dataItem.getPeriod(); double y = dataItem.getValue().doubleValue(); y *= scale;/* w w w . ja v a 2 s . co m*/ ds.update(period, y); } } return exp; }
From source file:edu.fullerton.viewerplugin.PluginSupport.java
public static void getRangeLimits(TimeSeriesCollection mtds, Double rng[]) { Double minx, miny, maxx, maxy; minx = miny = Double.MAX_VALUE; maxx = maxy = -Double.MAX_VALUE; for (Iterator it = mtds.getSeries().iterator(); it.hasNext();) { TimeSeries ds = (TimeSeries) it.next(); for (int item = 1; item < ds.getItemCount() - 1; item++) { TimeSeriesDataItem dataItem = ds.getDataItem(item); RegularTimePeriod period = dataItem.getPeriod(); double y = dataItem.getValue().doubleValue(); double x = period.getFirstMillisecond(); minx = Math.min(minx, x); miny = Math.min(miny, y); maxx = Math.max(maxx, x); maxy = Math.max(maxy, y); }//from w w w . ja va2 s . co m } rng[0] = minx; rng[1] = miny; rng[2] = maxx; rng[3] = maxy; }
From source file:de.xirp.chart.ChartUtil.java
/** * Exports the given dataset as CSV./* w w w. ja va2 s.c o m*/ * * @param dataset * The dataset to export. * @param robotName * The robot name for which the dataset is exported. * @see org.jfree.data.time.TimeSeriesCollection */ private static void exportCSV(TimeSeriesCollection dataset, String robotName) { for (Object obj : dataset.getSeries()) { List<Observed> obs = new ArrayList<Observed>(); TimeSeries ts = (TimeSeries) obj; String observedKey = (String) ts.getKey(); for (Object obj2 : ts.getItems()) { TimeSeriesDataItem tsdi = (TimeSeriesDataItem) obj2; Observed o = new Observed(); o.setObservedKey(observedKey); o.setTimestamp(tsdi.getPeriod().getStart().getTime()); o.setValue(tsdi.getValue().doubleValue()); obs.add(o); } exportCSV(obs, robotName); } }
From source file:net.sourceforge.openforecast.examples.ExponentialSmoothingChartDemo.java
/** * A helper function to convert data points (from startIndex to * endIndex) of a (JFreeChart) TimeSeries object into an * OpenForecast DataSet./*from w w w. j a va 2 s. co m*/ * @param series the series of data points stored as a JFreeChart * TimeSeries object. * @param startIndex the index of the first data point required from the * series. * @param endIndex the index of the last data point required from the * series. * @return an OpenForecast DataSet representing the data points extracted * from the TimeSeries. */ private DataSet getDataSet(TimeSeries series, int startIndex, int endIndex) { DataSet dataSet = new DataSet(); if (endIndex > series.getItemCount()) endIndex = series.getItemCount(); for (int i = startIndex; i < endIndex; i++) { TimeSeriesDataItem dataPair = series.getDataItem(i); DataPoint dp = new Observation(dataPair.getValue().doubleValue()); dp.setIndependentValue("t", i); dataSet.add(dp); } return dataSet; }
From source file:net.sourceforge.subsonic.controller.StatusChartController.java
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String type = request.getParameter("type"); int index = Integer.parseInt(request.getParameter("index")); List<TransferStatus> statuses = Collections.emptyList(); if ("stream".equals(type)) { statuses = statusService.getAllStreamStatuses(); } else if ("download".equals(type)) { statuses = statusService.getAllDownloadStatuses(); } else if ("upload".equals(type)) { statuses = statusService.getAllUploadStatuses(); }//from w ww.ja v a 2 s . c o m if (index < 0 || index >= statuses.size()) { return null; } TransferStatus status = statuses.get(index); TimeSeries series = new TimeSeries("Kbps", Millisecond.class); TransferStatus.SampleHistory history = status.getHistory(); long to = System.currentTimeMillis(); long from = to - status.getHistoryLengthMillis(); Range range = new DateRange(from, to); if (!history.isEmpty()) { TransferStatus.Sample previous = history.get(0); for (int i = 1; i < history.size(); i++) { TransferStatus.Sample sample = history.get(i); long elapsedTimeMilis = sample.getTimestamp() - previous.getTimestamp(); long bytesStreamed = Math.max(0L, sample.getBytesTransfered() - previous.getBytesTransfered()); double kbps = (8.0 * bytesStreamed / 1024.0) / (elapsedTimeMilis / 1000.0); series.addOrUpdate(new Millisecond(new Date(sample.getTimestamp())), kbps); previous = sample; } } // Compute moving average. series = MovingAverage.createMovingAverage(series, "Kbps", 20000, 5000); // Find min and max values. double min = 100; double max = 250; for (Object obj : series.getItems()) { TimeSeriesDataItem item = (TimeSeriesDataItem) obj; double value = item.getValue().doubleValue(); if (item.getPeriod().getFirstMillisecond() > from) { min = Math.min(min, value); max = Math.max(max, value); } } // Add 10% to max value. max *= 1.1D; // Subtract 10% from min value. min *= 0.9D; TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT); Paint background = new GradientPaint(0, 0, Color.lightGray, 0, IMAGE_HEIGHT, Color.white); plot.setBackgroundPaint(background); XYItemRenderer renderer = plot.getRendererForDataset(dataset); renderer.setSeriesPaint(0, Color.blue.darker()); renderer.setSeriesStroke(0, new BasicStroke(2f)); // Set theme-specific colors. Color bgColor = getBackground(request); Color fgColor = getForeground(request); chart.setBackgroundPaint(bgColor); ValueAxis domainAxis = plot.getDomainAxis(); domainAxis.setRange(range); domainAxis.setTickLabelPaint(fgColor); domainAxis.setTickMarkPaint(fgColor); domainAxis.setAxisLinePaint(fgColor); ValueAxis rangeAxis = plot.getRangeAxis(); rangeAxis.setRange(new Range(min, max)); rangeAxis.setTickLabelPaint(fgColor); rangeAxis.setTickMarkPaint(fgColor); rangeAxis.setAxisLinePaint(fgColor); ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, IMAGE_HEIGHT); return null; }
From source file:org.madsonic.controller.StatusChartController.java
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String type = request.getParameter("type"); int index = Integer.parseInt(request.getParameter("index")); List<TransferStatus> statuses = Collections.emptyList(); if ("stream".equals(type)) { statuses = statusService.getAllStreamStatuses(); } else if ("download".equals(type)) { statuses = statusService.getAllDownloadStatuses(); } else if ("upload".equals(type)) { statuses = statusService.getAllUploadStatuses(); }/* ww w. j av a 2s . c o m*/ if (index < 0 || index >= statuses.size()) { return null; } TransferStatus status = statuses.get(index); TimeSeries series = new TimeSeries("Kbps", Millisecond.class); TransferStatus.SampleHistory history = status.getHistory(); long to = System.currentTimeMillis(); long from = to - status.getHistoryLengthMillis(); Range range = new DateRange(from, to); if (!history.isEmpty()) { TransferStatus.Sample previous = history.get(0); for (int i = 1; i < history.size(); i++) { TransferStatus.Sample sample = history.get(i); long elapsedTimeMilis = sample.getTimestamp() - previous.getTimestamp(); long bytesStreamed = Math.max(0L, sample.getBytesTransfered() - previous.getBytesTransfered()); double kbps = (8.0 * bytesStreamed / 1024.0) / (elapsedTimeMilis / 1000.0); series.addOrUpdate(new Millisecond(new Date(sample.getTimestamp())), kbps); previous = sample; } } // Compute moving average. series = MovingAverage.createMovingAverage(series, "Kbps", 20000, 5000); // Find min and max values. double min = 100; double max = 250; for (Object obj : series.getItems()) { TimeSeriesDataItem item = (TimeSeriesDataItem) obj; double value = item.getValue().doubleValue(); if (item.getPeriod().getFirstMillisecond() > from) { min = Math.min(min, value); max = Math.max(max, value); } } // Add 10% to max value. max *= 1.1D; // Subtract 10% from min value. min *= 0.9D; TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT); Paint background = new GradientPaint(0, 0, Color.lightGray, 0, IMAGE_HEIGHT, Color.white); plot.setBackgroundPaint(background); XYItemRenderer renderer = plot.getRendererForDataset(dataset); renderer.setSeriesPaint(0, Color.gray.darker()); renderer.setSeriesStroke(0, new BasicStroke(2f)); // Set theme-specific colors. Color bgColor = getBackground(request); Color fgColor = getForeground(request); chart.setBackgroundPaint(bgColor); ValueAxis domainAxis = plot.getDomainAxis(); domainAxis.setRange(range); domainAxis.setTickLabelPaint(fgColor); domainAxis.setTickMarkPaint(fgColor); domainAxis.setAxisLinePaint(fgColor); ValueAxis rangeAxis = plot.getRangeAxis(); rangeAxis.setRange(new Range(min, max)); rangeAxis.setTickLabelPaint(fgColor); rangeAxis.setTickMarkPaint(fgColor); rangeAxis.setAxisLinePaint(fgColor); ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, IMAGE_HEIGHT); return null; }
From source file:it.eng.spagobi.engines.chart.bo.charttypes.targetcharts.WinLose.java
@Override public DatasetMap calculateValue() throws Exception { logger.debug("IN"); DatasetMap datasets = super.calculateValue(); if (datasets == null || yearsDefined == null) { logger.error("Error in TrargetCharts calculate value"); return null; }/*from w w w .j av a 2 s . c o m*/ DefaultCategoryDataset dataset = new DefaultCategoryDataset(); datasets.addDataset("1", dataset); if (datasets != null && yearsDefined.isEmpty()) { logger.warn("no rows found with dataset"); } else { // Check if defining target and baseline Double mainTarget = null; Double mainBaseline = null; if (mainThreshold == null) { logger.error("No main target or baseline defined, not possible to draw the chart"); } else { if (useTargets) mainTarget = mainThreshold; else mainBaseline = mainThreshold; nullValues = new Vector<String>(); // run all the years defined for (Iterator iterator = yearsDefined.iterator(); iterator.hasNext();) { String currentYearS = (String) iterator.next(); int currentYear = Integer.valueOf(currentYearS).intValue(); boolean stop = false; for (int i = 1; i < 13 && stop == false; i++) { Month currentMonth = new Month(i, currentYear); // if it is the first year and th ecurrent month is previous than the first month if (currentYearS.equalsIgnoreCase(yearsDefined.first()) && i < firstMonth.getMonth()) { // continue } else { TimeSeriesDataItem item = timeSeries.getDataItem(currentMonth); if (item != null && item.getValue() != null) { double v = item.getValue().doubleValue(); double result = 0; if (mainTarget != null) { result = (v >= mainTarget.doubleValue()) ? WIN : LOSE; } else if (mainBaseline != null) { result = (v > mainBaseline.doubleValue()) ? LOSE : WIN; } else { logger.warn("could not find a threshold"); } dataset.addValue(result, timeSeries.getKey(), "" + i + "-" + currentYear); } else { if (wlt_mode.doubleValue() == 5) { dataset.addValue(0.001, timeSeries.getKey(), "" + i + "-" + currentYear); nullValues.add("" + i + "-" + currentYear); } else { dataset.addValue(0.0, timeSeries.getKey(), "" + i + "-" + currentYear); } } // if it is last year and current month is after the last month stop if (currentYearS.equalsIgnoreCase(lastYear) && i >= lastMonth.getMonth()) { stop = true; } } } } } } logger.debug("OUT"); return datasets; }