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

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

Introduction

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

Prototype

public void addSeries(TimeSeries series) 

Source Link

Document

Adds a series to the collection and sends a DatasetChangeEvent to all registered listeners.

Usage

From source file:gov.llnl.lc.infiniband.opensm.plugin.gui.chart.PortCounterPlotWorker.java

private XYDataset createDeltaDataset(OSM_FabricDeltaCollection deltaHistory, PortCounterName pcn,
        String seriesName) {//from w w w.  ja  v a 2  s.com
    TimeSeries series = new TimeSeries(seriesName);

    // iterate through the collection, and build up a time series
    for (int j = 0; j < deltaHistory.getSize(); j++) {
        OSM_FabricDelta delta = deltaHistory.getOSM_FabricDelta(j);

        // find the desired port counter, in this instance
        LinkedHashMap<String, PFM_PortChange> pcL = delta.getPortChanges();
        PFM_PortChange pC = pcL.get(OSM_Port.getOSM_PortKey(Port));
        long lValue = pC.getDelta_port_counter(pcn);

        // correct for missing time periods
        int deltaSeconds = delta.getDeltaSeconds();
        long sweepPeriod = delta.getFabric2().getPerfMgrSweepSecs();
        if (sweepPeriod < deltaSeconds) {
            // graph is reported as counts per period, so if the period is too long, interpolate
            lValue *= sweepPeriod;
            lValue /= deltaSeconds;
        }
        TimeStamp ts = pC.getCounterTimeStamp();

        RegularTimePeriod ms = new FixedMillisecond(ts.getTimeInMillis());
        series.add(ms, (double) lValue);
    }
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);

    return dataset;
}

From source file:nu.nethome.home.items.web.GraphServlet.java

/**
* This is the main enterence point of the class. This is called when a http request is
* routed to this servlet.// w ww.  j a  v  a2s  . c  o  m
*/
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ServletOutputStream p = res.getOutputStream();
    Date startTime = null;
    Date stopTime = null;

    // Analyse arguments
    String fileName = req.getParameter("file");
    if (fileName != null)
        fileName = getFullFileName(fromURL(fileName));
    String startTimeString = req.getParameter("start");
    String stopTimeString = req.getParameter("stop");
    try {
        if (startTimeString != null) {
            startTime = m_Format.parse(startTimeString);
        }
        if (stopTimeString != null) {
            stopTime = m_Format.parse(stopTimeString);
        }
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
    String look = req.getParameter("look");
    if (look == null)
        look = "";

    TimeSeries timeSeries = new TimeSeries("Data", Minute.class);

    // Calculate time window
    Calendar cal = Calendar.getInstance();
    Date currentTime = cal.getTime();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    Date startOfDay = cal.getTime();
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    Date startOfWeek = cal.getTime();
    cal.set(Calendar.DAY_OF_MONTH, 1);
    Date startOfMonth = cal.getTime();
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    Date startOfYear = cal.getTime();

    // if (startTime == null) startTime = startOfWeek;
    if (stopTime == null)
        stopTime = currentTime;
    if (startTime == null)
        startTime = new Date(stopTime.getTime() - 1000L * 60L * 60L * 24L * 2L);

    try {
        // Open the data file
        File logFile = new File(fileName);
        Scanner fileScanner = new Scanner(logFile);
        Long startTimeMs = startTime.getTime();
        Long month = 1000L * 60L * 60L * 24L * 30L;
        boolean doOptimize = true;
        boolean justOptimized = false;
        try {
            while (fileScanner.hasNext()) {
                try {
                    // Get next log entry
                    String line = fileScanner.nextLine();
                    if (line.length() > 21) {
                        // Adapt the time format
                        String minuteTime = line.substring(0, 16).replace('.', '-');
                        // Parse the time stamp
                        Minute min = Minute.parseMinute(minuteTime);

                        // Ok, this is an ugly optimization. If the current time position in the file
                        // is more than a month (30 days) ahead of the start of the time window, we
                        // quick read two weeks worth of data, assuming that there is 4 samples per hour.
                        // This may lead to scanning past start of window if there are holes in the data
                        // series.
                        if (doOptimize && ((startTimeMs - min.getFirstMillisecond()) > month)) {
                            for (int i = 0; (i < (24 * 4 * 14)) && fileScanner.hasNext(); i++) {
                                fileScanner.nextLine();
                            }
                            justOptimized = true;
                            continue;
                        }
                        // Detect if we have scanned past the window start position just after an optimization scan.
                        // If this is the case it may be because of the optimization. In that case we have to switch 
                        // optimization off and start over.
                        if ((min.getFirstMillisecond() > startTimeMs) && doOptimize && justOptimized) {
                            logFile = new File(fileName);
                            fileScanner = new Scanner(logFile);
                            doOptimize = false;
                            continue;
                        }
                        justOptimized = false;
                        // Check if value is within time window
                        if ((min.getFirstMillisecond() > startTimeMs)
                                && (min.getFirstMillisecond() < stopTime.getTime())) {
                            // Parse the value
                            double value = Double.parseDouble((line.substring(20)).replace(',', '.'));
                            // Add the entry
                            timeSeries.add(min, value);
                            doOptimize = false;
                        }
                    }
                } catch (SeriesException se) {
                    // Bad entry, for example due to duplicates at daylight saving time switch
                } catch (NumberFormatException nfe) {
                    // Bad number format in a line, try to continue
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            fileScanner.close();
        }
    } catch (FileNotFoundException f) {
        System.out.println(f.toString());
    }

    // Create a collection for plotting
    TimeSeriesCollection data = new TimeSeriesCollection();
    data.addSeries(timeSeries);

    JFreeChart chart;

    int xSize = 750;
    int ySize = 450;
    // Customize colors and look of the Graph.
    if (look.equals("mobtemp")) {
        // Look for the mobile GUI
        chart = ChartFactory.createTimeSeriesChart(null, null, null, data, false, false, false);
        XYPlot plot = chart.getXYPlot();
        ValueAxis timeAxis = plot.getDomainAxis();
        timeAxis.setAxisLineVisible(false);
        ValueAxis valueAxis = plot.getRangeAxis(0);
        valueAxis.setAxisLineVisible(false);
        xSize = 175;
        ySize = 180;
    } else {
        // Create a Chart with time range as heading
        SimpleDateFormat localFormat = new SimpleDateFormat();
        String heading = localFormat.format(startTime) + " - " + localFormat.format(stopTime);
        chart = ChartFactory.createTimeSeriesChart(heading, null, null, data, false, false, false);

        Paint background = new Color(0x9D8140);
        chart.setBackgroundPaint(background);
        TextTitle title = chart.getTitle(); // fix title
        Font titleFont = title.getFont();
        titleFont = titleFont.deriveFont(Font.PLAIN, (float) 14.0);
        title.setFont(titleFont);
        title.setPaint(Color.darkGray);
        XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(background);
        plot.setDomainGridlinePaint(Color.darkGray);
        ValueAxis timeAxis = plot.getDomainAxis();
        timeAxis.setAxisLineVisible(false);
        ValueAxis valueAxis = plot.getRangeAxis(0);
        valueAxis.setAxisLineVisible(false);
        plot.setRangeGridlinePaint(Color.darkGray);
        XYItemRenderer renderer = plot.getRenderer(0);
        renderer.setSeriesPaint(0, Color.darkGray);
        xSize = 750;
        ySize = 450;
    }

    try {
        res.setContentType("image/png");
        res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "no-cache");
        res.setStatus(HttpServletResponse.SC_OK);
        ChartUtilities.writeChartAsPNG(p, chart, xSize, ySize);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }

    p.flush();
    p.close();
    return;
}

From source file:org.mwc.cmap.LiveDataMonitor.views.LiveDataMonitor.java

/**
 * The constructor./*  w w  w  . ja va2s . c  o  m*/
 */
public LiveDataMonitor() {
    _attListener = new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            // aah, is this for the scenario we're watching
            if (_myIndexedAttr != null)
                if (evt.getSource() == _myIndexedAttr.index) {

                    final DataDoublet newD = (DataDoublet) evt.getNewValue();
                    final long time = newD.getTime();
                    final Object newValue = newD.getValue();
                    if (newValue instanceof Number) {
                        final Number value = (Number) newValue;

                        // and store it
                        final TimeSeriesCollection coll = (TimeSeriesCollection) _chart.getXYPlot()
                                .getDataset();

                        TimeSeries tmpSeries;

                        if (coll == null) {
                            final TimeSeriesCollection dataset = new TimeSeriesCollection();
                            tmpSeries = new TimeSeries(_watchedAttr.getName());
                            dataset.addSeries(tmpSeries);
                            // add to series in different thread...
                            Display.getDefault().asyncExec(new Runnable() {
                                public void run() {
                                    _chart.getXYPlot().setDataset(dataset);
                                }
                            });
                        } else {
                            tmpSeries = coll.getSeries(0);
                        }

                        final TimeSeries series = tmpSeries;

                        // add to series in current thread, accepting it will slow down
                        // the
                        // UI
                        Display.getDefault().syncExec(new Runnable() {
                            public void run() {
                                // are we still open?i
                                if (!_chartFrame.isDisposed()) {
                                    // sure, go for it,
                                    series.addOrUpdate(new Millisecond(new Date(time)), value);
                                }
                            }
                        });
                    }
                }
        }
    };
}

From source file:DashboardInterface.LaunchGraph.java

public void addDataset(String title, int index, int range) {
    XYSplineRenderer render = new XYSplineRenderer();
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    TimeSeries series = new TimeSeries(title);
    dataset.addSeries(series);
    XYDataset xyDataset = dataset;//w  w  w  . j  a v  a2 s. c  om

    plot.setDataset(index, xyDataset);
    plot.setRenderer(index, render);

    NumberAxis axis = new NumberAxis(title);
    axis.setRange(0, range);

    plot.setRangeAxis(index, axis);
    plot.mapDatasetToRangeAxis(index, index);

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRendererForDataset(xyDataset);
    renderer.setBaseShapesVisible(false);
    renderer.setBaseShapesFilled(false);
}

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

/**
 * Processes requests for both HTTP//from  w  w w .  j av a 2s . c  om
 * <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");
    final String period = Default.toString(params.get("period"), "day");

    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) {
            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 (Exception e) {
                    log.error(e);
                }

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

    final String formatIn = getFormatIn(period);
    final String formatOut = getFormatOut(period);

    final Query q = ds.createQuery(MapReduceMinMax.class).disableValidation();

    final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from);
    final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to);

    final List<Date> datesIn = getRangeDate(dFrom, dTo);
    final HashSet<String> datesInString = new HashSet<String>();

    for (Date d : datesIn) {
        datesInString.add(DateTimeUtil.dateFormat(formatIn, d));
    }

    if (datesIn != null && !datesIn.isEmpty()) {
        q.filter("_id in", datesInString);
    }
    q.order("_id");

    final List<MapReduceMinMax> mapReduceResult = q.asList();
    final TimeSeries serieMin = new TimeSeries("Min");
    final TimeSeries serieMax = new TimeSeries("Max");

    for (MapReduceMinMax m : mapReduceResult) {
        try {

            final Date tmpDate = DateTimeUtil.getDate(formatIn, m.getId().toString());
            if (tmpDate == null) {
                continue;
            }

            final Millisecond t = new Millisecond(tmpDate);

            ChartEnumMinMaxHelper chartEnum = ChartEnumMinMaxHelper.getByFieldAndType(field, "min");
            Method method = m.getClass().getMethod(chartEnum.getMethod());
            Number n = (Number) method.invoke(m);
            serieMin.add(t, n);

            chartEnum = ChartEnumMinMaxHelper.getByFieldAndType(field, "max");
            method = m.getClass().getMethod(chartEnum.getMethod());
            n = (Number) method.invoke(m);
            serieMax.add(t, n);

        } catch (IllegalAccessException ex) {
            log.error(ex);
        } catch (IllegalArgumentException ex) {
            log.error(ex);
        } catch (InvocationTargetException ex) {
            log.error(ex);
        } catch (NoSuchMethodException ex) {
            log.error(ex);
        } catch (SecurityException ex) {
            log.error(ex);
        }
    }

    final ChartEnumMinMaxHelper chartData = ChartEnumMinMaxHelper.getByFieldAndType(field, "min");

    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(serieMin);
    dataset.addSeries(serieMax);

    final JFreeChart chart = ChartFactory.createTimeSeriesChart("Max/Min", "", chartData.getUm(), dataset, true,
            false, false);
    final XYPlot plot = (XYPlot) chart.getPlot();
    final DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat(formatOut));

    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 (Exception e) {
        log.error(e);
    } finally {
        f.delete();
    }

}

From source file:lu.lippmann.cdb.common.gui.ts.TimeSeriesChartUtil.java

private static void fillWithSingleAxis(final Instances dataSet, final int dateIdx,
        final TimeSeriesCollection tsDataset) {
    final int numInstances = dataSet.numInstances();

    final Calendar cal = Calendar.getInstance();
    for (final Integer i : WekaDataStatsUtil.getNumericAttributesIndexes(dataSet)) {
        if (dataSet.attributeStats(i).missingCount == dataSet.numInstances()) {
            System.out.println("TimeSeriesChartUtil: Only missing values for '" + dataSet.attribute(i).name()
                    + "', so skip it!");
            continue;
        }//from ww w  .ja  va 2s.c o  m
        final TimeSeries ts = new TimeSeries(dataSet.attribute(i).name());
        for (int k = 0; k < numInstances; k++) {
            final Instance instancek = dataSet.instance(k);
            final long timeInMilliSec = (long) instancek.value(dateIdx);
            cal.setTimeInMillis(timeInMilliSec);

            if (instancek.isMissing(i)) {
                ts.addOrUpdate(new Millisecond(cal.getTime()), null);
            } else {
                ts.addOrUpdate(new Millisecond(cal.getTime()), instancek.value(i));
            }
        }
        if (!ts.isEmpty())
            tsDataset.addSeries(ts);
    }
}

From source file:dpnm.netmsuite.plc.manager.frontend.graph.TimeSeriesChartDemo1.java

/**
 * Creates a dataset, consisting of two series of monthly data.
 * @return The dataset.//from   w  ww . j av a 2s  .co  m
 */
private XYDataset createDataset() {

    /*
     * each 5 seconds, the data updated...
     * 
     */
    String firstGraph = "";
    String secondGraph = "";

    if (graphType == 1) {
        firstGraph = "InPackets";
        secondGraph = "OutPackets";

        TimeSeries s1 = new TimeSeries(firstGraph, Second.class);
        for (int i = 1; i < statisticInfos.size(); i++) {
            StatisticInfo pastInfo = (StatisticInfo) statisticInfos.elementAt(i - 1);
            StatisticInfo oneInfo = (StatisticInfo) statisticInfos.elementAt(i);
            long timeStamp = oneInfo._timeStamp;
            long gap = (oneInfo._timeStamp - pastInfo._timeStamp) / 1000;
            gap = gap == 0 ? 1 : gap;
            Date date = new Date(timeStamp);
            long inPkts = oneInfo._inPkts - pastInfo._inPkts;
            if (inPkts < 0) {
                pastInfo._inPkts = oneInfo._inPkts + 2 ^ 32 - pastInfo._inPkts;
            }
            inPkts = inPkts / gap;
            s1.add(new Second(date), inPkts);
        }

        TimeSeries s2 = new TimeSeries(secondGraph, Second.class);
        for (int i = 1; i < statisticInfos.size(); i++) {
            StatisticInfo pastInfo = (StatisticInfo) statisticInfos.elementAt(i - 1);
            StatisticInfo oneInfo = (StatisticInfo) statisticInfos.elementAt(i);
            long timeStamp = oneInfo._timeStamp;
            long gap = (oneInfo._timeStamp - pastInfo._timeStamp) / 1000;
            gap = gap == 0 ? 1 : gap;
            Date date = new Date(timeStamp);
            long outPkts = oneInfo._outPkts - pastInfo._outPkts;
            if (outPkts < 0) {
                pastInfo._outPkts = oneInfo._outPkts + 2 ^ 32 - pastInfo._outPkts;
            }
            outPkts = outPkts / gap;
            s2.add(new Second(date), outPkts);
        }

        TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(s1);
        dataset.addSeries(s2);

        dataset.setDomainIsPointsInTime(true);
        return dataset;
    } else if (graphType == 2) {
        firstGraph = "InBytes";
        secondGraph = "OutBytes";

        TimeSeries s1 = new TimeSeries(firstGraph, Second.class);
        for (int i = 1; i < statisticInfos.size(); i++) {
            StatisticInfo pastInfo = (StatisticInfo) statisticInfos.elementAt(i - 1);
            StatisticInfo oneInfo = (StatisticInfo) statisticInfos.elementAt(i);
            long timeStamp = oneInfo._timeStamp;
            long gap = (oneInfo._timeStamp - pastInfo._timeStamp) / 1000;
            gap = gap == 0 ? 1 : gap;
            Date date = new Date(timeStamp);
            long _inBytes = oneInfo._inBytes - pastInfo._inBytes;
            if (_inBytes < 0) {
                pastInfo._inBytes = oneInfo._inBytes + 2 ^ 32 - pastInfo._inBytes;
            }
            _inBytes = _inBytes / gap;
            s1.add(new Second(date), _inBytes);
        }

        TimeSeries s2 = new TimeSeries(secondGraph, Second.class);
        for (int i = 1; i < statisticInfos.size(); i++) {
            StatisticInfo pastInfo = (StatisticInfo) statisticInfos.elementAt(i - 1);
            StatisticInfo oneInfo = (StatisticInfo) statisticInfos.elementAt(i);
            long timeStamp = oneInfo._timeStamp;
            long gap = (oneInfo._timeStamp - pastInfo._timeStamp) / 1000;
            gap = gap == 0 ? 1 : gap;
            Date date = new Date(timeStamp);
            long _outBytes = oneInfo._outBytes - pastInfo._outBytes;
            if (_outBytes < 0) {
                pastInfo._outBytes = oneInfo._outBytes + 2 ^ 32 - pastInfo._outBytes;
            }
            _outBytes = _outBytes / gap;
            s2.add(new Second(date), _outBytes);
        }

        TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(s1);
        dataset.addSeries(s2);

        dataset.setDomainIsPointsInTime(true);
        return dataset;
    } else if (graphType == 3) {
        firstGraph = "InSpeed";
        secondGraph = "OutSpeed";

        TimeSeries s1 = new TimeSeries(firstGraph, Second.class);
        for (int i = 1; i < statisticInfos.size(); i++) {
            StatisticInfo pastInfo = (StatisticInfo) statisticInfos.elementAt(i - 1);
            StatisticInfo oneInfo = (StatisticInfo) statisticInfos.elementAt(i);
            long timeStamp = oneInfo._timeStamp;
            Date date = new Date(timeStamp);
            long _inSpeed = oneInfo._inSpeed;
            s1.add(new Second(date), _inSpeed);
        }

        TimeSeries s2 = new TimeSeries(secondGraph, Second.class);
        for (int i = 1; i < statisticInfos.size(); i++) {
            StatisticInfo pastInfo = (StatisticInfo) statisticInfos.elementAt(i - 1);
            StatisticInfo oneInfo = (StatisticInfo) statisticInfos.elementAt(i);
            long timeStamp = oneInfo._timeStamp;
            Date date = new Date(timeStamp);
            long _outSpeed = oneInfo._outSpeed;

            s2.add(new Second(date), _outSpeed);
        }

        TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(s1);
        dataset.addSeries(s2);

        dataset.setDomainIsPointsInTime(true);
        return dataset;
    } else {
        firstGraph = "Not Defiend";
        secondGraph = "Not Defiend";
        return null;
    }
}

From source file:com.view.TimeSeriesChartView.java

public JFreeChart getVendorTimeSeriesChart(Excel theExcel, String vendor) {
    int vendorCode = Integer.parseInt(vendor);
    ArrayList<Receiving> theReceiving = theExcel.getSheetReceiving();

    //        HashMap<Month, Integer> item1Map = new HashMap<>();
    //        HashMap<Month, Integer> item2Map = new HashMap<>();
    //        HashMap<Month, Integer> item3Map = new HashMap<>();
    Set vendorItem = new HashSet();
    for (int i = 0; i < theReceiving.size(); i++) {
        vendorItem.add(theReceiving.get(i).getItem());
    }/*from   ww w.ja v a  2 s  .  c om*/
    TimeSeries data[] = new TimeSeries[vendorItem.size()];
    HashMap<Month, Integer> itemMap[] = new HashMap[vendorItem.size()];
    for (int i = 0; i < vendorItem.size(); i++) {
        String itemName = "item" + i;
        data[i] = new TimeSeries(itemName);
        itemMap[i] = new HashMap<>();
    }
    Calendar cal = Calendar.getInstance();
    for (int i = 0; i < theReceiving.size(); i++) {
        cal.setTime(theReceiving.get(i).getDate());
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        int quantity = 0;
        if (theReceiving.get(i).getVendor() == vendorCode) {
            quantity = theReceiving.get(i).getQuantity();
            Month theMonth = new Month(month, year);
            int itemNum = theReceiving.get(i).getItem() - 1;
            itemMap[itemNum].put(theMonth, updateItemMap(itemMap[itemNum], theMonth, quantity));
        }
    }
    TimeSeriesCollection my_data_series = new TimeSeriesCollection();
    for (int i = 0; i < vendorItem.size(); i++) {
        for (Map.Entry<Month, Integer> entry : itemMap[i].entrySet()) {
            data[i].add(entry.getKey(), entry.getValue());
        }
        my_data_series.addSeries(data[i]);
    }

    JFreeChart chart = ChartFactory.createTimeSeriesChart("Receiving", "Month", "Quantity", my_data_series,
            true, true, false);
    chart.setBackgroundPaint(Color.YELLOW);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.GREEN);
    plot.setRangeGridlinePaint(Color.orange);
    plot.setAxisOffset(new RectangleInsets(50, 0, 20, 5));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();

    renderer.setBaseShapesVisible(true);
    renderer.setBaseShapesFilled(true);

    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("MM.yyyy"));
    return chart;
}

From source file:ChartUsingJava.CombinedXYPlotDemo1.java

/**
 * Creates a sample dataset.  You wouldn't normally hard-code the
 * population of a dataset in this way (it would be better to read the
 * values from a file or a database query), but for a self-contained demo
 * this is the least complicated solution.
 *
 * @return A sample dataset.//from  w  w w.j  a va 2 s  . c o m
 */
private static IntervalXYDataset createDataset2() {
    TimeSeriesCollection dataset = new TimeSeriesCollection();

    TimeSeries series1 = new TimeSeries("Series 2");
    series1.add(new Month(1, 2005), 1200);
    series1.add(new Month(2, 2005), 1400);
    series1.add(new Month(3, 2005), 1500);
    series1.add(new Month(4, 2005), 1700);
    series1.add(new Month(5, 2005), 1600);
    series1.add(new Month(6, 2005), 2400);
    series1.add(new Month(7, 2005), 2100);
    series1.add(new Month(8, 2005), 2200);
    series1.add(new Month(9, 2005), 800);
    series1.add(new Month(10, 2005), 2350);
    series1.add(new Month(11, 2005), 500);
    series1.add(new Month(12, 2005), 700);
    series1.add(new Month(1, 2006), 900);
    series1.add(new Month(2, 2006), 1500);
    series1.add(new Month(3, 2006), 2100);
    series1.add(new Month(4, 2006), 2200);
    series1.add(new Month(5, 2006), 1900);
    series1.add(new Month(6, 2006), 3000);
    series1.add(new Month(7, 2006), 3780);
    series1.add(new Month(8, 2006), 4000);
    series1.add(new Month(9, 2006), 4500);
    series1.add(new Month(10, 2006), 7000);
    series1.add(new Month(11, 2006), 5500);
    series1.add(new Month(12, 2006), 6000);
    series1.add(new Month(1, 2007), 6500);
    dataset.addSeries(series1);
    return dataset;

}

From source file:de.xirp.chart.ChartManager.java

/**
 * This method creates a/* ww  w  .  j  a  v a 2 s. c om*/
 * {@link org.jfree.data.time.TimeSeriesCollection} from the given
 * {@link de.xirp.db.Record} and key array. The
 * record is evaluated from the given start to the given stop time
 * or is evaluated completely if the flag <code>origTime</code>
 * is set to <code>true</code>. <br>
 * <br>
 * The method also fills the given
 * <code>List&lt;Observed&gt;</code> with the found
 * {@link de.xirp.db.Observed} value objects. This
 * list is used by the
 * {@link de.xirp.chart.ChartManager#exportAutomatically(List, JFreeChart)}
 * method. <br>
 * <br>
 * This is done because the code base is the the. The
 * {@link de.xirp.db.Observed} objects are created
 * from a database query. To create a chart the date must be
 * contained in a {@link org.jfree.data.time.TimeSeriesCollection}.
 * The export methods in
 * {@link de.xirp.chart.ChartUtil} works with a
 * <code>List&lt;Observed&gt;</code>. The database query
 * delivers a <code>List&lt;Observed&gt;</code>, so the values
 * are converted to a
 * {@link org.jfree.data.time.TimeSeriesCollection} and then are
 * copied to the <code>all</code> list to be used laster on in
 * the
 * {@link de.xirp.chart.ChartManager#exportAutomatically(List, JFreeChart)}
 * method.
 * 
 * @param all
 *            <code>null</code> or empty List <b>not</b>
 *            permitted.<br>
 *            Must be a <code>new</code> List.
 * @param record
 *            The record containing the data.
 * @param keys
 *            The keys to use.
 * @param origTime
 *            A flag indicating if the original time should be
 *            used.
 * @param stop
 *            The start time.
 * @param start
 *            The stop time.
 * @return A <code>TimeSeriesCollection</code> with the values
 *         of the record for the time interval.
 * @see org.jfree.data.time.TimeSeriesCollection
 * @see de.xirp.db.Observed
 * @see de.xirp.db.Record
 * @see de.xirp.chart.ChartUtil
 * @see de.xirp.chart.ChartManager#exportAutomatically(java.util.List,
 *      org.jfree.chart.JFreeChart)
 * @see org.jfree.chart.JFreeChart
 */
private static TimeSeriesCollection createTimeSeriesAndFillAllObservedList(List<Observed> all, Record record,
        String[] keys, boolean origTime, long start, long stop) {

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    Date date = new Date();
    List<Observed> obs;
    for (String keyname : keys) {
        TimeSeries ts = new TimeSeries(keyname, Millisecond.class);
        if (origTime) {
            obs = ChartDatabaseUtil.getObservedList(record, keyname);
        } else {
            obs = ChartDatabaseUtil.getObservedList(record, keyname, start, stop);
        }
        for (Observed o : obs) {
            date.setTime(o.getTimestamp());
            ts.addOrUpdate(new Millisecond(date), o.getValue());
        }
        all.addAll(obs);
        dataset.addSeries(ts);
    }
    return dataset;
}