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

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

Introduction

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

Prototype

@Override
public int getItemCount() 

Source Link

Document

Returns the number of items in the series.

Usage

From source file:com.charts.ThreeMonthChart.java

public ThreeMonthChart(YStockQuote currentStock) throws ParseException {

    DateAxis domainAxis = new DateAxis("Date");
    NumberAxis rangeAxis = new NumberAxis("Price");
    CandlestickRenderer renderer = new CandlestickRenderer();
    XYDataset dataset = getDataSet(currentStock);

    XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

    //Do some setting up, see the API Doc
    renderer.setSeriesPaint(0, Color.BLACK);
    renderer.setDrawVolume(false);//from w  ww .j a  v a  2  s  .  co m
    rangeAxis.setAutoRangeIncludesZero(false);

    domainAxis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yy"));
    domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);

    //Now create the chart and chart panel
    JFreeChart chart = new JFreeChart(currentStock.get_name(), null, mainPlot, false);
    chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new Dimension(600, 300));

    XYPlot plot = (XYPlot) chart.getPlot();
    LegendTitle legend = new LegendTitle(plot);
    chart.addLegend(legend);
    chart.getLegend().setVisible(true);
    chart.getLegend().setPosition(RectangleEdge.BOTTOM);
    ValueAxis yAxis = (ValueAxis) plot.getRangeAxis();
    DateAxis xAxis = (DateAxis) plot.getDomainAxis();
    Date now = new Date();
    SegmentedTimeline segmentedTimeline = SegmentedTimeline.newMondayThroughFridayTimeline();
    Calendar[][] holidays = DayRange.getHolidayDates();
    int len = holidays.length;

    for (int i = 0; i < holidays[0].length; i++) {
        Calendar day = Calendar.getInstance(TimeZone.getTimeZone("EST"));
        day.set(Calendar.YEAR, holidays[0][i].get(Calendar.YEAR));
        day.set(Calendar.MONTH, holidays[0][i].get(Calendar.MONTH));
        day.set(Calendar.DAY_OF_MONTH, holidays[0][i].get(Calendar.DAY_OF_MONTH));
        day.set(Calendar.HOUR_OF_DAY, 9);
        segmentedTimeline.addException(day.getTime());

    }

    xAxis.setTimeline(segmentedTimeline);
    //xAxis.setVerticalTickLabels(true);
    xAxis.setDateFormatOverride(new SimpleDateFormat("MMM y"));
    xAxis.setAutoTickUnitSelection(true);
    xAxis.setAutoRange(true);
    renderer.setAutoWidthFactor(0.5);
    renderer.setUpPaint(Color.green);
    renderer.setDownPaint(new Color(0xc0, 0x00, 0x00));
    renderer.setSeriesPaint(0, Color.black);

    StandardXYItemRenderer renderer1 = new StandardXYItemRenderer();
    renderer1.setSeriesPaint(0, Color.BLUE);
    TimeSeries movingAverage30 = MovingAverage.createMovingAverage(close, "MA(30)", 30, 0);
    Double currMA30 = (Double) movingAverage30.getDataItem(movingAverage30.getItemCount() - 1).getValue();
    currMA30 = Math.round(currMA30 * 100.0) / 100.0;
    movingAverage30.setKey("MA(30): " + currMA30);
    TimeSeriesCollection collection = new TimeSeriesCollection();
    collection.addSeries(movingAverage30);
    plot.setDataset(1, collection);
    plot.setRenderer(1, renderer1);

    chartPanel.revalidate();
    chartPanel.repaint();
    chartPanel.revalidate();
    chartPanel.repaint();
}

From source file:com.charts.OneMonthChart.java

public OneMonthChart(YStockQuote currentStock) throws ParseException {

    DateAxis domainAxis = new DateAxis("Date");
    NumberAxis rangeAxis = new NumberAxis("Price");
    CandlestickRenderer renderer = new CandlestickRenderer();
    XYDataset dataset = getDataSet(currentStock);

    XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

    //Do some setting up, see the API Doc
    renderer.setSeriesPaint(0, Color.BLACK);
    renderer.setDrawVolume(false);/*ww  w.  j a  va 2s . c  o  m*/
    rangeAxis.setAutoRangeIncludesZero(false);

    domainAxis.setVerticalTickLabels(true);
    domainAxis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yy"));
    domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);

    //Now create the chart and chart panel
    JFreeChart chart = new JFreeChart(currentStock.get_name(), null, mainPlot, false);
    chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new Dimension(600, 300));

    XYPlot plot = (XYPlot) chart.getPlot();
    LegendTitle legend = new LegendTitle(plot);
    chart.addLegend(legend);
    chart.getLegend().setVisible(true);
    chart.getLegend().setPosition(RectangleEdge.BOTTOM);

    ValueAxis yAxis = (ValueAxis) plot.getRangeAxis();
    DateAxis xAxis = (DateAxis) plot.getDomainAxis();
    Date now = new Date();
    SegmentedTimeline segmentedTimeline = SegmentedTimeline.newMondayThroughFridayTimeline();
    Calendar[][] holidays = DayRange.getHolidayDates();
    int len = holidays.length;

    for (int i = 0; i < holidays[0].length; i++) {
        Calendar day = Calendar.getInstance(TimeZone.getTimeZone("EST"));
        day.set(Calendar.YEAR, holidays[0][i].get(Calendar.YEAR));
        day.set(Calendar.MONTH, holidays[0][i].get(Calendar.MONTH));
        day.set(Calendar.DAY_OF_MONTH, holidays[0][i].get(Calendar.DAY_OF_MONTH));
        day.set(Calendar.HOUR_OF_DAY, 9);
        segmentedTimeline.addException(day.getTime());

    }

    xAxis.setTimeline(segmentedTimeline);
    //xAxis.setVerticalTickLabels(true);
    xAxis.setDateFormatOverride(new SimpleDateFormat("MMM-dd"));
    xAxis.setAutoTickUnitSelection(false);
    xAxis.setAutoRange(false);
    renderer.setAutoWidthFactor(0.5);
    renderer.setUpPaint(Color.green);
    renderer.setDownPaint(new Color(0xc0, 0x00, 0x00));
    renderer.setSeriesPaint(0, Color.black);

    StandardXYItemRenderer renderer1 = new StandardXYItemRenderer();
    renderer1.setSeriesPaint(0, Color.BLUE);
    TimeSeries movingAverage30 = MovingAverage.createMovingAverage(close, "MA(30)", 30, 0);
    Double currMA30 = (Double) movingAverage30.getDataItem(movingAverage30.getItemCount() - 1).getValue();
    currMA30 = Math.round(currMA30 * 100.0) / 100.0;
    movingAverage30.setKey("MA(30): " + currMA30);
    TimeSeriesCollection collection = new TimeSeriesCollection();
    collection.addSeries(movingAverage30);
    plot.setDataset(1, collection);
    plot.setRenderer(1, renderer1);

    chartPanel.revalidate();
    chartPanel.repaint();
    chartPanel.revalidate();
    chartPanel.repaint();
}

From source file:com.charts.SixMonthChart.java

public SixMonthChart(YStockQuote currentStock) throws ParseException {

    DateAxis domainAxis = new DateAxis("Date");
    NumberAxis rangeAxis = new NumberAxis("Price");
    CandlestickRenderer renderer = new CandlestickRenderer();
    XYDataset dataset = getDataSet(currentStock);

    XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

    //Do some setting up, see the API Doc
    renderer.setSeriesPaint(0, Color.BLACK);
    renderer.setDrawVolume(false);// w  w w  .  j  a  va2 s  . c  o m
    rangeAxis.setAutoRangeIncludesZero(false);

    domainAxis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yy"));
    domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);

    //Now create the chart and chart panel
    JFreeChart chart = new JFreeChart(currentStock.get_name(), null, mainPlot, false);
    chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new Dimension(600, 300));

    XYPlot plot = (XYPlot) chart.getPlot();

    LegendTitle legend = new LegendTitle(plot);

    chart.addLegend(legend);
    chart.getLegend().setVisible(true);
    chart.getLegend().setPosition(RectangleEdge.BOTTOM);

    ValueAxis yAxis = (ValueAxis) plot.getRangeAxis();
    DateAxis xAxis = (DateAxis) plot.getDomainAxis();
    Date now = new Date();
    SegmentedTimeline segmentedTimeline = SegmentedTimeline.newMondayThroughFridayTimeline();
    Calendar[][] holidays = DayRange.getHolidayDates();
    int len = holidays.length;

    for (int i = 0; i < holidays[0].length; i++) {
        Calendar day = Calendar.getInstance(TimeZone.getTimeZone("EST"));
        day.set(Calendar.YEAR, holidays[0][i].get(Calendar.YEAR));
        day.set(Calendar.MONTH, holidays[0][i].get(Calendar.MONTH));
        day.set(Calendar.DAY_OF_MONTH, holidays[0][i].get(Calendar.DAY_OF_MONTH));
        day.set(Calendar.HOUR_OF_DAY, 9);
        segmentedTimeline.addException(day.getTime());

    }

    xAxis.setTimeline(segmentedTimeline);
    //xAxis.setVerticalTickLabels(true);
    xAxis.setDateFormatOverride(new SimpleDateFormat("MMM y"));
    xAxis.setAutoTickUnitSelection(true);
    xAxis.setAutoRange(true);
    renderer.setAutoWidthFactor(0.5);
    renderer.setUpPaint(Color.green);
    renderer.setDownPaint(new Color(0xc0, 0x00, 0x00));
    renderer.setSeriesPaint(0, Color.black);

    StandardXYItemRenderer renderer1 = new StandardXYItemRenderer();
    renderer1.setSeriesPaint(0, Color.BLUE);
    TimeSeries movingAverage30 = MovingAverage.createMovingAverage(close, "MA(30)", 30, 0);
    Double currMA30 = (Double) movingAverage30.getDataItem(movingAverage30.getItemCount() - 1).getValue();
    currMA30 = Math.round(currMA30 * 100.0) / 100.0;
    movingAverage30.setKey("MA(30): " + currMA30);
    TimeSeriesCollection collection = new TimeSeriesCollection();
    collection.addSeries(movingAverage30);
    plot.setDataset(1, collection);
    plot.setRenderer(1, renderer1);

    chartPanel.revalidate();
    chartPanel.repaint();
    chartPanel.revalidate();
    chartPanel.repaint();
}

From source file:com.hello2morrow.sonargraph.jenkinsplugin.model.TimeSeriesPlot.java

/**
 * Creates a XYDataset from a CSV file./*from   w ww.ja  v a 2 s. c  om*/
 */
@Override
protected XYDataset createXYDataset(SonargraphMetrics metric, int maximumNumberOfDataPoints)
        throws IOException {
    assert metric != null : "Parameter 'metric' of method 'createXYDataset' must not be null";

    //For some reason, the class of the time series is required here, otherwise an exception is thrown that a Date instance is expected.
    @SuppressWarnings("deprecation")
    TimeSeries timeSeries = new TimeSeries(metric.getShortDescription(), FixedMillisecond.class);

    List<IDataPoint> dataset = m_datasetProvider.readMetricValues(metric);
    int size = dataset.size();
    SonargraphLogger.INSTANCE.fine(size + " data points found for metric '" + metric.getStandardName()
            + "' in file '" + m_datasetProvider.getStorageName() + "'");
    List<IDataPoint> reducedSet = reduceDataSet(dataset, maximumNumberOfDataPoints);

    BuildDataPoint point = null;
    for (IDataPoint datapoint : reducedSet) {
        if (datapoint instanceof InvalidDataPoint) {
            // We could create a gap in the graph by adding null:
            // xySeries.add(datapoint.getX(), null);
            continue;
        } else if (datapoint instanceof BuildDataPoint) {
            point = (BuildDataPoint) datapoint;
            if (point.getTimestamp() == 0) {
                continue;
            }

            timeSeries.add(new FixedMillisecond(point.getTimestamp()), point.getY());
        }
    }
    if (point != null) {
        setTimestampOfLastDisplayedPoint(point.getTimestamp());
    }

    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();
    TimeSeries avgDataset = MovingAverage.createMovingAverage(timeSeries,
            "Avg of " + metric.getShortDescription(), MOVING_AVG_PERIOD, 0);
    setDataSetSize(avgDataset.getItemCount());
    timeSeriesCollection.addSeries(avgDataset);

    //SG-325: We cannot use JFreeChart methods of version 1.0.14
    //        setMinimumValue(avgDataset.getMinY());
    //        setMaximumValue(avgDataset.getMaxY());

    // We only show the average data and omit the original data
    //        timeSeriesCollection.addSeries(timeSeries);
    for (Object item : avgDataset.getItems()) {
        if (item instanceof TimeSeriesDataItem) {
            checkMinMaxYValue(((TimeSeriesDataItem) item).getValue().doubleValue());
        }
    }
    return timeSeriesCollection;
}

From source file:org.mwc.cmap.grideditor.chart.JFreeChartComposite.java

@Override
public void mouseDoubleClick(final MouseEvent event) {
    final Rectangle scaledDataArea = getScreenDataArea(event.x, event.y);
    if (scaledDataArea == null)
        return;//from ww w  .  j ava 2s. co m
    int x = (int) ((event.x - getClientArea().x) / getScaleX());
    int y = (int) ((event.y - getClientArea().y) / getScaleY());
    x = (int) ((event.x - getClientArea().x));
    y = (int) ((event.y - getClientArea().y));

    if (this.getChartRenderingInfo() != null) {
        final EntityCollection entities = this.getChartRenderingInfo().getEntityCollection();
        if (entities != null) {
            for (final Object next : entities.getEntities()) {
                final ChartEntity nextEntity = (ChartEntity) next;
                if (false == nextEntity instanceof XYItemEntity) {
                    continue;
                }

                if (nextEntity.getArea().contains(x, y)) {
                    // sort out it's details
                    final XYItemEntity xyEntity = (XYItemEntity) nextEntity;
                    int theIndex = 0;
                    if (xyEntity.getDataset() instanceof XYSeriesCollection) {
                        theIndex = xyEntity.getItem();

                        //                     BackedChartItem backedChartItem;
                        //                     XYSeries series = ((XYSeriesCollection) xyEntity.getDataset())
                        //                           .getSeries(seriesKey);
                        //                     XYDataItem dataItem = series.getDataItem(xyEntity.getItem());
                        //                     if (dataItem instanceof BackedChartItem)
                        //                     {
                        //                        backedChartItem = (BackedChartItem) dataItem;
                        //                     }
                    } else if (xyEntity.getDataset() instanceof TimeSeriesCollection) {
                        final TimeSeriesCollection theDataset = (TimeSeriesCollection) xyEntity.getDataset();
                        final TimeSeries theSeries = theDataset.getSeries(xyEntity.getSeriesIndex());
                        theIndex = xyEntity.getItem();
                        final int itemCount = theSeries.getItemCount();
                        // the items are in reverse order. reverse the index
                        theIndex = itemCount - (theIndex + 1);

                        // TimeSeries series = ((TimeSeriesCollection)
                        // xyEntity.getDataset())
                        // .getSeries(seriesKey);
                        // TimeSeriesDataItem dataItem = series
                        // .getDataItem(xyEntity.getItem());
                        // if (dataItem instanceof BackedChartItem)
                        // {
                        // backedChartItem = (BackedChartItem) dataItem;
                        // }
                    }

                    // clear the selection, as long as ctrl isn't selected
                    if ((event.stateMask & SWT.CTRL) != 0) {
                        // control is selected, so we don't want to clear the selection
                    } else if ((event.stateMask & SWT.SHIFT) != 0) {
                        // shift is selected, so we want to extend the selection
                    } else {
                        // we're not extending the selection, clear it,
                        _dataGrid.getTableViewer().getTable().deselectAll();
                    }

                    // try to select it
                    _dataGrid.getTableViewer().getTable().select(theIndex);

                    // and make sure it's visible
                    _dataGrid.getTableViewer().getTable().showSelection();

                    // and tell the action buttons what's happened
                    _dataGrid.getActionContext().setSelection(_dataGrid.getTableViewer().getSelection());

                    break;
                }
            }
        }
    }
}

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

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

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

                StringBuilder b = new StringBuilder();

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

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

From source file:com.jaxzin.iraf.forecast.swing.JForecaster.java

@SuppressWarnings({ "MethodWithMultipleLoops" })
protected XYDataset createDataset() {
    final TimeSeriesCollection tsc = new TimeSeriesCollection();

    //        long start = System.currentTimeMillis();
    Forecast forecastData = null;// w w  w.j a v a  2 s .  c o  m
    try {
        //            System.out.println("Generating dataset; initial salary is <"+domain.getInitialSalary()+">");
        forecastData = forecaster.forecast(domain);
    } catch (ForecastException e) {
        e.printStackTrace();
    }

    int count = 1;
    assert forecastData != null;
    final int total = forecastData.getForecastData().size() + 1;
    //noinspection ForLoopThatDoesntUseLoopVariable
    for (Iterator i = forecastData.getForecastData().iterator(); i.hasNext(); count++) {
        final List<Money> universeData = (List<Money>) i.next();
        //noinspection ObjectAllocationInLoop,UnqualifiedStaticUsage
        final TimeSeries ts = new TimeSeries(new StringBuilder()
                .append(String.valueOf((count * TOTAL_PERCENTILES) / total)).append("th").toString(),
                Year.class);
        for (Money money : universeData) {
            if (ts.getItemCount() == 0) {
                //noinspection ObjectAllocationInLoop
                ts.add(RegularTimePeriod.createInstance(Year.class, new Date(), TimeZone.getDefault()),
                        money.doubleValue());
            } else {
                ts.add(ts.getNextTimePeriod(), money.doubleValue());
            }
        }

        tsc.addSeries(ts);

    }
    //        System.out.println(System.currentTimeMillis()-start);

    return tsc;
}

From source file:edu.fullerton.viewerplugin.TsPlot.java

private TimeSeries LinFit(TimeSeries ts) {
    TimeSeries ret = new TimeSeries("lin fit", Millisecond.class);
    SimpleTimeZone utctz = new SimpleTimeZone(0, "UTC");
    int n = ts.getItemCount();
    double[] x = new double[n];
    double[] y = new double[n];
    TimeSeriesDataItem it;// www.ja v  a2s .c  o m
    for (int i = 0; i < n; i++) {
        it = ts.getDataItem(i);
        x[i] = it.getPeriod().getFirstMillisecond() + 0.;
        y[i] = it.getValue().doubleValue();
    }
    LinearRegression lr = new LinearRegression(x, y);
    double b = lr.getIntercept();
    double m = lr.getSlope();
    double fit, t;
    for (int i = 0; i < n; i++) {
        it = ts.getDataItem(i);
        t = it.getPeriod().getFirstMillisecond() + 0.;
        fit = m * t + b;

        ret.addOrUpdate(it.getPeriod(), fit);
    }

    return ret;
}

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

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

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

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

}

From source file:org.paxle.tools.charts.impl.gui.ChartServlet.java

@SuppressWarnings("unchecked")
public Iterator<RegularTimePeriod> getMergedPeriods(List<TimeSeries> seriesList) {
    TreeSet<RegularTimePeriod> periods = new TreeSet<RegularTimePeriod>();

    for (TimeSeries series : seriesList) {
        if (series.getItemCount() == 0)
            continue;
        periods.addAll(series.getTimePeriods());
    }// ww w  . j a v  a  2s. co m

    return periods.iterator();
}