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

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

Introduction

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

Prototype

public void add(RegularTimePeriod period, Number value) 

Source Link

Document

Adds a new data item to the series and sends a org.jfree.data.general.SeriesChangeEvent to all registered listeners.

Usage

From source file:com.geminimobile.chart.GeminiChartUtil.java

public void createReport(OutputStream out, List<ChartSeries> chartData, String strTitle,
        String strDomainAxisLabel) {

    strDomainAxisLabel = "Time Interval: " + strDomainAxisLabel;
    String strYAxisLabel;/*from   w  w w.j av a2 s  .  co  m*/
    //String strCategoryType = " ";
    strYAxisLabel = "Count";
    //SimpleDateFormat sdf = new SimpleDateFormat("MMMM-dd hh:mm a");

    //build a dataset as needed by JFreeChart
    //      note: strCategoryType is for a chart with multiple categories.
    //      i.e. idisplay multiple bars for each time interval.
    //

    TimeSeriesCollection dataSet = new TimeSeriesCollection();

    // For each series of data, create a TimeSeries
    for (int i = 0; i < chartData.size(); i++) {
        ChartSeries chartSeries = chartData.get(i);

        TimeSeries timeSeries = new TimeSeries(chartSeries.getName(), Millisecond.class);
        List<ChartValueByTime> data = chartSeries.getData();

        //int cumulValue = 0;
        for (int j = 0; j < data.size(); j++) {
            ChartValueByTime chartVal = data.get(j);

            Millisecond ms = new Millisecond(new Date(chartVal.getTime()));

            // *NOT* Store the cumulative value . So maintain a running total.                
            //cumulValue += chartVal.getValue();
            //timeSeries.add(ms, cumulValue);
            timeSeries.add(ms, chartVal.getValue());
        }
        dataSet.addSeries(timeSeries);
    }

    JFreeChart lineChart = ChartFactory.createTimeSeriesChart(strTitle, // chart title
            strDomainAxisLabel, // domain axis label
            strYAxisLabel, // range axis label
            dataSet, // data
            true, // legend
            false, // tooltips
            false // urls
    );

    try {
        ChartUtilities.writeChartAsPNG(out, lineChart, 800, 400);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:eu.planets_project.tb.impl.chart.ExperimentChartServlet.java

/**
 * Creates a sample time series chart./*from  ww  w  .j  a va  2s.c om*/
 *
 * @return a time series chart.
 */
private JFreeChart createTimeSeriesChart() {

    // here we just populate a series with random data...
    TimeSeries series = new TimeSeries("Random Data");
    Day current = new Day(1, MonthConstants.JANUARY, 2001);
    for (int i = 0; i < 100; i++) {
        series.add(current, Math.random() * 100);
        current = (Day) current.next();
    }

    XYDataset data = new TimeSeriesCollection(series);

    JFreeChart chart = ChartFactory.createTimeSeriesChart("Time Series Chart", "Date", "Rate", data, true, true,
            false);

    return chart;

}

From source file:com.bdb.weather.display.summary.RainSummary.java

/**
 * Load the data into the plot.// ww  w .  j  a v a 2  s .c om
 * 
 * @param list The summary data
 */
public void loadData(List<SummaryRecord> list) {
    dataTable.setItems(FXCollections.observableList(list));
    TimeSeriesCollection ds = new TimeSeriesCollection();
    TimeSeries etSeries = new TimeSeries(ET_ROW_KEY);
    TimeSeries rainSeries = new TimeSeries(RAIN_ROW_KEY);

    Depth totalRain = new Depth(0.0);
    Depth totalET = new Depth(0.0);

    //
    // Load each record
    //
    for (SummaryRecord rec : list) {
        Depth rain = rec.getTotalRainfall();

        RegularTimePeriod tp = RegularTimePeriod.createInstance(interval.getFreeChartClass(),
                TimeUtils.localDateTimeToDate(rec.getDate()), TimeZone.getDefault());

        if (rain != null) {
            rainSeries.add(tp, rain.get());
            totalRain = totalRain.add(rain);
        }

        Depth et = rec.getTotalET();
        if (et != null) {
            etSeries.add(tp, et.get());
            totalET = totalET.add(et);
        }
    }

    ds.addSeries(etSeries);
    ds.addSeries(rainSeries);
    rainPlot.setDataset(ds);
}

From source file:de.tsystems.mms.apm.performancesignature.ui.PerfSigBuildActionResultsDisplay.java

public void doSummarizerGraph(final StaplerRequest request, final StaplerResponse response) throws IOException {
    final Graph graph = new GraphImpl(request, getBuild().getTimestamp().getTimeInMillis()) {
        @Override/*w  w w .  java2  s.c o  m*/
        protected TimeSeriesCollection createDataSet() {
            String measure = request.getParameter("measure");
            String chartDashlet = request.getParameter("chartdashlet");
            String testCase = request.getParameter("testcase");
            TimeSeries timeSeries = new TimeSeries(chartDashlet, Second.class);

            DashboardReport dashboardReport = getDashBoardReport(testCase);
            Measure m = dashboardReport.getMeasure(chartDashlet, measure);
            if (m == null || m.getMeasurements() == null) {
                return null;
            }

            for (Measurement measurement : m.getMeasurements()) {
                timeSeries.add(new Second(new Date(measurement.getTimestamp())),
                        measurement.getMetricValue(m.getAggregation()));
            }
            return new TimeSeriesCollection(timeSeries);
        }
    };
    graph.doPng(request, response);
}

From source file:sernet.gs.ui.rcp.main.bsi.views.chart.RealisierungLineChart.java

private Object createProgressDataset() throws CommandException {
    TimeSeries ts1 = new TimeSeries(Messages.RealisierungLineChart_7, Day.class);
    TimeSeries ts2 = new TimeSeries(Messages.RealisierungLineChart_8, Day.class);

    RealisierungSummary command = new RealisierungSummary();
    command = ServiceFactory.lookupCommandService().executeCommand(command);

    DateValues dateTotal1 = command.getTotal1();
    DateValues dateTotal2 = command.getTotal2();

    Map<Day, Integer> totals1 = dateTotal1.getDateTotals();
    Set<Entry<Day, Integer>> entrySet1 = totals1.entrySet();
    for (Entry<Day, Integer> entry : entrySet1) {
        ts1.add(entry.getKey(), entry.getValue());
    }//from  ww  w .ja va2s .  co m

    Map<Day, Integer> totals2 = dateTotal2.getDateTotals();
    Set<Entry<Day, Integer>> entrySet2 = totals2.entrySet();
    for (Entry<Day, Integer> entry : entrySet2) {
        ts2.add(entry.getKey(), entry.getValue());
    }

    TimeSeriesCollection tsc = new TimeSeriesCollection();
    tsc.addSeries(ts2);
    tsc.addSeries(ts1);
    return tsc;
}

From source file:de.codesourcery.eve.skills.ui.components.impl.PriceHistoryComponent.java

private TimeSeries calcMovingAverage(String name, List<PriceInfo> data, MovingAverage dateRange) {

    // group price infos by days
    final Map<Date, List<PriceInfo>> pricesByDay = new HashMap<Date, List<PriceInfo>>();

    for (PriceInfo info : data) {
        if (info.getAveragePrice() == 0) {
            continue;
        }//w  w w.  j  a  v a 2s .c  o m

        final Date stripped = DateHelper.stripTime(info.getTimestamp().getLocalTime());
        List<PriceInfo> existing = pricesByDay.get(stripped);
        if (existing == null) {
            existing = new ArrayList<PriceInfo>();
            pricesByDay.put(stripped, existing);
        }
        existing.add(info);
    }

    // calculate daily averages
    final Map<Date, Double> averages = new HashMap<Date, Double>();

    for (Map.Entry<Date, List<PriceInfo>> entry : pricesByDay.entrySet()) {

        double amount = 0;
        for (PriceInfo info : entry.getValue()) {
            amount += info.getAveragePrice();
        }
        double average = amount / entry.getValue().size();
        averages.put(entry.getKey(), average);
    }

    // sort averages ascending by dates 
    final List<Date> dates = new ArrayList<Date>();
    dates.addAll(averages.keySet());
    Collections.sort(dates);

    if (dates.size() <= 2) {
        return null;
    }

    /*
     * For each date between
     * 'earliest' and 'latest':
     * 
     *  Calculate the average from this 
     *  day and the previous 4 days.
     */
    final Date latest = dates.get(dates.size() - 1);
    final Date earliest = dates.get(0);

    final Calendar current = Calendar.getInstance();
    current.setTime(latest);

    final Map<Date, Double> movingAverage = new HashMap<Date, Double>();

    // TODO: Not a very efficient implementation....
    final int days = dateRange.getDays();
    do {
        int count = 0;
        double sum = 0;

        Calendar loop = Calendar.getInstance();
        loop.setTime(current.getTime());
        for (int i = 0; i < days; i++) {
            Double avg = averages.get(loop.getTime());
            if (avg != null) {
                count++;
                sum += avg;
            }
            loop.add(Calendar.DAY_OF_MONTH, -1);
        }

        if (count > 0) {
            final double average = (sum / 100.0d) / (double) count;
            movingAverage.put(current.getTime(), average);
        }

        current.add(Calendar.DAY_OF_MONTH, -1);
    } while (current.getTime().compareTo(earliest) >= 0);

    final TimeSeries result = new TimeSeries(name);
    for (Map.Entry<Date, Double> entry : movingAverage.entrySet()) {
        result.add(new Day(entry.getKey()), entry.getValue());
    }
    return result;
}

From source file:edu.unibonn.kmeans.mapreduce.plotting.TimeSeriesPlotter_KMeans.java

private XYDataset createDataset(ArrayList<Cluster_KMeans> clusters, LocalDateTime from) {
    final TimeSeriesCollection dataset = new TimeSeriesCollection();

    //      for (int i = 0; i < clusters.size(); i++)
    //      {//  w ww.  j  a  v  a  2s .  com
    //         Cluster_KMeans current_cluster = clusters.get(i);   
    //         double[] center_of_mass = current_cluster.getCenter_of_mass();
    //         
    //         final TimeSeries s1 = new TimeSeries("Cluster_"+current_cluster.getCluster_id(), Hour.class);
    //
    //         for (int j = 0; j < 24; j++)
    //         {
    //            s1.add(new Hour( j, from.getDayOfMonth(), from.getMonthValue(), from.getYear() ), center_of_mass[j]);
    //         }
    //         
    //         dataset.addSeries(s1);
    //      }

    for (int i = 0; i < clusters.size(); i++) {
        Cluster_KMeans current_cluster = clusters.get(i);
        ArrayList<Day_24d> member_time_series = current_cluster.getMembership();

        for (Iterator iterator = member_time_series.iterator(); iterator.hasNext();) {
            final TimeSeries s1 = new TimeSeries("Cluster_" + current_cluster.getCluster_id(), Hour.class);

            Day_24d current_series = (Day_24d) iterator.next();

            for (int j = 0; j < 24; j++) {
                s1.add(new Hour(j, from.getDayOfMonth(), from.getMonthValue(), from.getYear()),
                        current_series.getMeasurement(j));
            }

            dataset.addSeries(s1);
        }
    }

    dataset.setDomainIsPointsInTime(true);

    return dataset;
}

From source file:org.streamspinner.harmonica.application.CQGraphTerminal.java

private TimeSeries updateTimeSeries(String name, int col, double val) {
    TimeSeries ts = c.getSeries(name);

    if (ts == null) {
        ts = new TimeSeries(name, Millisecond.class);
        ts.setMaximumItemCount(100);//  w w  w. java2 s .  c  om
        col_series_map.put(col, ts);
        c.addSeries(ts);
    }

    if (Double.isNaN(val)) {
        ts.add(getMillisecond(), null);
    } else {
        ts.add(getMillisecond(), val);
    }
    return ts;
}

From source file:it.marcoberri.mbmeteo.action.chart.Get.java

/**
 * Processes requests for both HTTP/*from  w  w w .j  ava 2  s. c  o m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);
    final String from = Default.toString(params.get("from") + " 00:00:00", "1970-01-01 00:00:00");
    final String to = Default.toString(params.get("to") + " 23:59:00", "2030-01-01 23:59:00");
    final String field = Default.toString(params.get("field"), "outdoorTemperature");

    request.getSession().setAttribute("from", params.get("from"));
    request.getSession().setAttribute("to", params.get("to"));

    final String cacheKey = getCacheKey(params);

    if (cacheReadEnable) {
        final Query q = ds.find(Cache.class);
        q.filter("cacheKey", cacheKey).filter("servletName", this.getClass().getName());

        final Cache c = (Cache) q.get();

        if (c == null) {
            log.info("cacheKey:" + cacheKey + " on servletName: " + this.getClass().getName() + " not found");
        }

        if (c != null) {
            log.debug("get file from cache id: " + c.getGridId());
            final GridFSDBFile imageForOutput = MongoConnectionHelper.getGridFS()
                    .findOne(new ObjectId(c.getGridId()));
            if (imageForOutput != null) {

                ds.save(c);

                try {
                    response.setHeader("Content-Length", "" + imageForOutput.getLength());
                    response.setHeader("Content-Disposition",
                            "inline; filename=\"" + imageForOutput.getFilename() + "\"");
                    final OutputStream out = response.getOutputStream();
                    final InputStream in = imageForOutput.getInputStream();
                    final byte[] content = new byte[(int) imageForOutput.getLength()];
                    in.read(content);
                    out.write(content);
                    in.close();
                    out.close();
                    return;
                } catch (final IOException e) {
                    log.error(e);
                }

            } else {
                log.error("file not in db");
            }
        }
    }

    final String titleChart = ChartEnumHelper.getByName(field).getTitle();
    final String umChart = ChartEnumHelper.getByName(field).getUm();
    final Query q = ds.createQuery(Meteolog.class);
    final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from);
    final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to);

    q.disableValidation().filter("time >=", dFrom).filter("time <=", dTo);

    final List<Meteolog> meteoLogList = q.asList();
    final TimeSeries series = new TimeSeries(umChart);

    for (Meteolog m : meteoLogList) {
        final Millisecond t = new Millisecond(m.getTime());
        try {
            //violenza di una reflection
            final Method method = m.getClass().getMethod(ChartEnumHelper.getByName(field).getMethod());
            final Number n = (Number) method.invoke(m);
            series.add(t, n);
        } catch (final NoSuchMethodException ex) {
            log.error(ex);
        } catch (final InvocationTargetException ex) {
            log.error(ex);
        } catch (final IllegalAccessException ex) {
            log.error(ex);
        } catch (final SecurityException ex) {
            log.error(ex);
        }

    }

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

    final JFreeChart chart = ChartFactory.createTimeSeriesChart(titleChart, "", umChart, dataset, false, false,
            false);
    final XYPlot plot = (XYPlot) chart.getPlot();
    final DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy HH:mm"));
    axis.setVerticalTickLabels(true);

    if (field.toUpperCase().indexOf("PRESSURE") != -1) {
        plot.getRangeAxis().setRange(chartPressureMin, chartPressureMax);
    }

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy);

    try {

        if (cacheWriteEnable) {

            final GridFSInputFile gfsFile = MongoConnectionHelper.getGridFS().createFile(f);
            gfsFile.setFilename(f.getName());
            gfsFile.save();

            final Cache c = new Cache();
            c.setServletName(this.getClass().getName());
            c.setCacheKey(cacheKey);
            c.setGridId(gfsFile.getId().toString());

            ds.save(c);

        }

        response.setContentType("image/jpeg");
        response.setHeader("Content-Length", "" + f.length());
        response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
        final OutputStream out = response.getOutputStream();
        final FileInputStream in = new FileInputStream(f.toString());
        final int size = in.available();
        final byte[] content = new byte[size];
        in.read(content);
        out.write(content);
        in.close();
        out.close();
    } catch (final IOException e) {
        log.error(e);
    } finally {
        f.delete();
    }

}

From source file:org.gbif.portal.web.controller.dataset.IndexingHistoryController.java

/**
 * Create a time series graphic to display indexing processes.
 * //  w  w w  .ja  va  2  s. c o  m
 * @param dataProvider
 * @param dataResource
 * @param activities
 * @param fileNamePrefix
 * @return
 */
public String timeSeriesTest(DataProviderDTO dataProvider, DataResourceDTO dataResource,
        List<LoggedActivityDTO> loggedActivities, String fileNamePrefix, int minProcessingTimeToRender) {

    List<LoggedActivityDTO> activities = new ArrayList<LoggedActivityDTO>();
    for (LoggedActivityDTO la : loggedActivities) {
        if (la.getDataResourceKey() != null && la.getDataResourceName() != null && la.getEventName() != null)
            activities.add(la);
    }

    //if no activities to render, return
    if (activities.isEmpty())
        return null;

    Map<String, Integer> drActualCount = new HashMap<String, Integer>();
    Map<String, Integer> drCount = new HashMap<String, Integer>();

    //record the actual counts
    for (LoggedActivityDTO laDTO : activities) {
        if (laDTO.getStartDate() != null && laDTO.getEndDate() != null
                && laDTO.getDurationInMillisecs() > minProcessingTimeToRender) {
            if (drActualCount.get(laDTO.getDataResourceName()) == null) {
                drActualCount.put(laDTO.getDataResourceName(), new Integer(4));
                drCount.put(laDTO.getDataResourceName(), new Integer(0));
            } else {
                Integer theCount = drActualCount.get(laDTO.getDataResourceName());
                theCount = new Integer(theCount.intValue() + 4);
                drActualCount.remove(laDTO.getDataResourceName());
                drActualCount.put(laDTO.getDataResourceName(), theCount);
            }
        }
    }

    StringBuffer fileNameBuffer = new StringBuffer(fileNamePrefix);
    if (dataResource != null) {
        fileNameBuffer.append("-resource-");
        fileNameBuffer.append(dataResource.getKey());
    } else if (dataProvider != null) {
        fileNameBuffer.append("-provider-");
        fileNameBuffer.append(dataProvider.getKey());
    }
    fileNameBuffer.append(".png");

    String fileName = fileNameBuffer.toString();
    String filePath = System.getProperty("java.io.tmpdir") + File.separator + fileName;

    File fileToCheck = new File(filePath);
    if (fileToCheck.exists()) {
        return fileName;
    }

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    boolean generateChart = false;

    int count = 1;
    int dataResourceCount = 1;

    Collections.sort(activities, new Comparator<LoggedActivityDTO>() {
        public int compare(LoggedActivityDTO o1, LoggedActivityDTO o2) {
            if (o1 == null || o2 == null || o1.getDataResourceKey() != null || o2.getDataResourceKey() != null)
                return -1;
            return o1.getDataResourceKey().compareTo(o2.getDataResourceKey());
        }
    });

    String currentDataResourceKey = activities.get(0).getDataResourceKey();

    for (LoggedActivityDTO laDTO : activities) {
        if (laDTO.getStartDate() != null && laDTO.getEndDate() != null
                && laDTO.getDurationInMillisecs() > minProcessingTimeToRender) {

            if (currentDataResourceKey != null && !currentDataResourceKey.equals(laDTO.getDataResourceKey())) {
                dataResourceCount++;
                count = count + 1;
                currentDataResourceKey = laDTO.getDataResourceKey();
            }
            TimeSeries s1 = new TimeSeries(laDTO.getDataResourceName(), "Process time period",
                    laDTO.getEventName(), Hour.class);
            s1.add(new Hour(laDTO.getStartDate()), count);
            s1.add(new Hour(laDTO.getEndDate()), count);
            dataset.addSeries(s1);
            generateChart = true;
        }
    }

    if (!generateChart)
        return null;

    // create a pie chart...
    final JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false);

    XYPlot plot = chart.getXYPlot();
    plot.setWeight(10);
    plot.getRangeAxis().setAutoRange(false);
    plot.getRangeAxis().setRange(0, drCount.size() + 1);
    plot.getRangeAxis().setAxisLineVisible(false);
    plot.getRangeAxis().setAxisLinePaint(Color.WHITE);
    plot.setDomainCrosshairValue(1);
    plot.setRangeGridlinesVisible(false);
    plot.getRangeAxis().setVisible(false);
    plot.getRangeAxis().setLabel("datasets");

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setItemLabelsVisible(true);
    MyXYItemLabelGenerator labelGenerator = new MyXYItemLabelGenerator();
    labelGenerator.setDataResourceActualCount(drActualCount);
    labelGenerator.setDataResourceCount(drCount);
    renderer.setItemLabelGenerator(labelGenerator);

    List<TimeSeries> seriesList = dataset.getSeries();
    for (TimeSeries series : seriesList) {
        if (((String) series.getRangeDescription()).startsWith("extraction")) {
            renderer.setSeriesPaint(seriesList.indexOf(series), Color.RED);
        } else {
            renderer.setSeriesPaint(seriesList.indexOf(series), Color.BLUE);
        }
        renderer.setSeriesStroke(seriesList.indexOf(series), new BasicStroke(7f));
    }

    int imageHeight = 30 * dataResourceCount;
    if (imageHeight < 100) {
        imageHeight = 100;
    } else {
        imageHeight = imageHeight + 100;
    }

    final BufferedImage image = new BufferedImage(900, imageHeight, BufferedImage.TYPE_INT_RGB);
    KeypointPNGEncoderAdapter adapter = new KeypointPNGEncoderAdapter();
    adapter.setQuality(1);
    try {
        adapter.encode(image);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    final Graphics2D g2 = image.createGraphics();
    g2.setFont(new Font("Arial", Font.PLAIN, 11));
    final Rectangle2D chartArea = new Rectangle2D.Double(0, 0, 900, imageHeight);

    // draw
    chart.draw(g2, chartArea, null, null);

    //styling
    chart.setPadding(new RectangleInsets(0, 0, 0, 0));
    chart.setBorderVisible(false);
    chart.setBackgroundImageAlpha(0);
    chart.setBackgroundPaint(Color.WHITE);
    chart.setBorderPaint(Color.LIGHT_GRAY);

    try {
        FileOutputStream fOut = new FileOutputStream(filePath);
        ChartUtilities.writeChartAsPNG(fOut, chart, 900, imageHeight);
        return fileName;
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}