Example usage for org.jfree.chart.plot XYPlot getDataset

List of usage examples for org.jfree.chart.plot XYPlot getDataset

Introduction

In this page you can find the example usage for org.jfree.chart.plot XYPlot getDataset.

Prototype

public XYDataset getDataset(int index) 

Source Link

Document

Returns the dataset with the specified index, or null if there is no dataset with that index.

Usage

From source file:org.griphyn.vdl.karajan.monitor.monitors.swing.GraphPanel.java

private void addSeries(Series<?> series) {
    Unit unit = series.getUnit();//www  .ja v  a  2 s .co m
    XYPlot plot = chart.getXYPlot();
    Integer datasetIndex = datasetMapping.get(unit);
    TimeSeriesCollection col;
    if (datasetIndex == null) {
        col = new TimeSeriesCollection();
        int nextIndex = getNextDatasetIndex(plot);
        datasetMapping.put(unit, nextIndex);
        plot.setDataset(nextIndex, col);
        plot.setRenderer(nextIndex, new XYLineAndShapeRenderer(true, false));

        NumberAxis axis = new AutoNumberAxis(unit);
        plot.setRangeAxis(nextIndex, axis);
        plot.mapDatasetToRangeAxis(nextIndex, nextIndex);

        seriesMapping.put(unit, new ArrayList<String>());
    } else {
        col = (TimeSeriesCollection) plot.getDataset(datasetIndex);
    }
    TimeSeries ts = new SeriesWrapper(series, sampler);
    seriesMapping.get(unit).add(series.getKey());
    col.addSeries(ts);
    setColor(series.getKey(), palette.allocate());
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private boolean updateROIPoint(Point2D _ROIPoint) {
    if (_ROIPoint == null) {
        return false;
    }//  ww w . java 2  s.  c  o m

    final ChartPanel chartPanel = this.investmentFlowChartJDialog.getChartPanel();
    final JFreeChart chart = chartPanel.getChart();
    final XYPlot plot = (XYPlot) chart.getPlot();
    // Dataset 0 are the invest information. 1 is the ROI information.
    final TimeSeriesCollection timeSeriesCollection = (TimeSeriesCollection) plot.getDataset(1);
    final TimeSeries timeSeries = timeSeriesCollection.getSeries(0);

    // I also not sure why. This is what are being done in Mouse Listener Demo 4.
    //
    // Don't use it. It will cause us to lose precision.
    //final Point2D p2 = chartPanel.translateScreenToJava2D((Point)_ROIPoint);

    /* Try to get correct main chart area. */
    final Rectangle2D _plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();

    /* Believe it? When there is another thread keep updateing time series data,
     * and keep calling setDirty, _plotArea can be 0 size sometimes. Ignore it.
     * Just assume we had processed it.
     */
    if (_plotArea.getWidth() == 0.0 && _plotArea.getHeight() == 0.0) {
        /* Cheat the caller. */
        return true;
    }

    final ValueAxis domainAxis = plot.getDomainAxis();
    final RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    final ValueAxis rangeAxis = plot.getRangeAxis();
    final RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();
    final double coordinateX = domainAxis.java2DToValue(_ROIPoint.getX(), _plotArea, domainAxisEdge);

    int low = 0;
    int high = timeSeries.getItemCount() - 1;
    Date date = new Date((long) coordinateX);
    final long time = date.getTime();
    long bestDistance = Long.MAX_VALUE;
    int bestMid = 0;

    while (low <= high) {
        int mid = (low + high) >>> 1;

        final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(mid);
        final Day day = (Day) timeSeriesDataItem.getPeriod();
        final long search = day.getFirstMillisecond();
        final long cmp = search - time;

        if (cmp < 0) {
            low = mid + 1;
        } else if (cmp > 0) {
            high = mid - 1;
        } else {
            bestDistance = 0;
            bestMid = mid;
            break;
        }

        final long abs_cmp = Math.abs(cmp);
        if (abs_cmp < bestDistance) {
            bestDistance = abs_cmp;
            bestMid = mid;
        }
    }

    final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(bestMid);
    final double xValue = timeSeriesDataItem.getPeriod().getFirstMillisecond();
    final double yValue = timeSeriesDataItem.getValue().doubleValue();
    final double xJava2D = domainAxis.valueToJava2D(xValue, _plotArea, domainAxisEdge);
    final double yJava2D = rangeAxis.valueToJava2D(yValue, _plotArea, rangeAxisEdge);

    final int tmpIndex = bestMid;
    // Do not perform translation as this will cause precision losing.
    // We might experience unstable point. For example,
    //
    // this.ROIPoint is 700.9, there are 2 data points which are 700 and
    // 701.
    // During first updateROIPoint(this.ROIPoint) call, data point 701
    // will be chosen, and this.ROIPoint has been truncated to 700.
    // During second updateROIPoint(this.ROIPoint) call, data point 700
    // will be chosen. We may observe an unstable point swings between 700
    // and 701.
    //
    // translateJava2DToScreen will internally convert Point2D.Double to Point.
    //final Point2D tmpPoint = chartPanel.translateJava2DToScreen(new Point2D.Double(xJava2D, yJava2D));
    final Point2D tmpPoint = new Point2D.Double(xJava2D, yJava2D);
    this.drawArea.setRect(_plotArea);

    if (this.drawArea.contains(tmpPoint)) {
        this.ROIPointIndex = tmpIndex;
        this.ROIPoint = tmpPoint;
        return true;
    }
    return false;
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private Point2D.Double getPoint(int dataIndex, Type type) {
    if (dataIndex < 0) {
        return null;
    }/*from w  ww .  j a  va 2 s  .  com*/

    final ChartPanel chartPanel = this.investmentFlowChartJDialog.getChartPanel();
    final JFreeChart chart = chartPanel.getChart();
    final XYPlot plot = (XYPlot) chart.getPlot();
    // Dataset 0 are the invest information. 1 is the ROI information.
    final TimeSeriesCollection timeSeriesCollection;
    if (type == Type.Invest) {
        timeSeriesCollection = (TimeSeriesCollection) plot.getDataset(0);
    } else {
        assert (type == Type.ROI);
        timeSeriesCollection = (TimeSeriesCollection) plot.getDataset(1);
    }
    final TimeSeries timeSeries = timeSeriesCollection.getSeries(0);

    if (dataIndex >= timeSeries.getItemCount()) {
        /* Not ready yet. */
        return null;
    }

    final ValueAxis domainAxis = plot.getDomainAxis();
    final RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    final ValueAxis rangeAxis = plot.getRangeAxis();
    final RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();

    final TimeSeriesDataItem timeSeriesDataItem = timeSeries.getDataItem(dataIndex);
    final double xValue = timeSeriesDataItem.getPeriod().getFirstMillisecond();
    final double yValue = timeSeriesDataItem.getValue().doubleValue();
    final Rectangle2D plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();
    final double xJava2D = domainAxis.valueToJava2D(xValue, plotArea, domainAxisEdge);
    final double yJava2D = rangeAxis.valueToJava2D(yValue, plotArea, rangeAxisEdge);
    // Use Double version, to avoid from losing precision.
    return new Point2D.Double(xJava2D, yJava2D);
}

From source file:org.yccheok.jstock.gui.charting.ChartLayerUI.java

private Point2D.Double _getPointForCandlestick(int plotIndex, int seriesIndex, int dataIndex) {
    final ChartPanel chartPanel = this.chartJDialog.getChartPanel();
    final XYPlot plot = this.chartJDialog.getPlot(plotIndex);
    final ValueAxis domainAxis = plot.getDomainAxis();
    final RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
    final ValueAxis rangeAxis = plot.getRangeAxis();
    final RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();

    final org.jfree.data.xy.DefaultHighLowDataset defaultHighLowDataset = (org.jfree.data.xy.DefaultHighLowDataset) plot
            .getDataset(seriesIndex);//from  w  ww.  j  ava  2 s .c o  m

    if (dataIndex >= defaultHighLowDataset.getItemCount(0)) {
        /* Not ready yet. */
        return null;
    }

    final double xValue = defaultHighLowDataset.getXDate(0, dataIndex).getTime();
    final double yValue = defaultHighLowDataset.getCloseValue(0, dataIndex);
    final Rectangle2D plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getSubplotInfo(plotIndex)
            .getDataArea();
    final double xJava2D = domainAxis.valueToJava2D(xValue, plotArea, domainAxisEdge);
    final double yJava2D = rangeAxis.valueToJava2D(yValue, plotArea, rangeAxisEdge);
    // Use Double version, to avoid from losing precision.
    return new Point2D.Double(xJava2D, yJava2D);
}

From source file:edu.dlnu.liuwenpeng.render.XYLineAndShapeRenderer.java

/**    
 * Returns a legend item for the specified series.    
 *    /*w w  w  .j a va2 s.c  om*/
 * @param datasetIndex  the dataset index (zero-based).    
 * @param series  the series index (zero-based).    
 *    
 * @return A legend item for the series.    
 */
public LegendItem getLegendItem(int datasetIndex, int series) {

    XYPlot plot = getPlot();
    if (plot == null) {
        return null;
    }

    LegendItem result = null;
    XYDataset dataset = plot.getDataset(datasetIndex);
    if (dataset != null) {
        if (getItemVisible(series, 0)) {
            String label = getLegendItemLabelGenerator().generateLabel(dataset, series);
            String description = label;
            String toolTipText = null;
            if (getLegendItemToolTipGenerator() != null) {
                toolTipText = getLegendItemToolTipGenerator().generateLabel(dataset, series);
            }
            String urlText = null;
            if (getLegendItemURLGenerator() != null) {
                urlText = getLegendItemURLGenerator().generateLabel(dataset, series);
            }
            boolean shapeIsVisible = getItemShapeVisible(series, 0);
            Shape shape = lookupSeriesShape(series);
            boolean shapeIsFilled = getItemShapeFilled(series, 0);
            Paint fillPaint = (this.useFillPaint ? lookupSeriesFillPaint(series) : lookupSeriesPaint(series));
            boolean shapeOutlineVisible = this.drawOutlines;
            Paint outlinePaint = (this.useOutlinePaint ? lookupSeriesOutlinePaint(series)
                    : lookupSeriesPaint(series));
            Stroke outlineStroke = lookupSeriesOutlineStroke(series);
            boolean lineVisible = getItemLineVisible(series, 0);
            Stroke lineStroke = lookupSeriesStroke(series);
            Paint linePaint = lookupSeriesPaint(series);
            result = new LegendItem(label, description, toolTipText, urlText, shapeIsVisible, shape,
                    shapeIsFilled, fillPaint, shapeOutlineVisible, outlinePaint, outlineStroke, lineVisible,
                    this.legendLine, lineStroke, linePaint);
            result.setSeriesKey(dataset.getSeriesKey(series));
            result.setSeriesIndex(series);
            result.setDataset(dataset);
            result.setDatasetIndex(datasetIndex);
        }
    }

    return result;

}

From source file:edu.cmu.sv.modelinference.eventtool.EventVisualizer.java

private void visualizeClasses(ClassificationResult classes, Map<EventClass, Color> clusterColors) {
    DataChart clustersDataChart = new DataChart("Classification chart");
    JFreeChart clusterChart = clustersDataChart.chart("");
    XYPlot clusterPlot = clusterChart.getXYPlot();

    int dataSetIndex = 0;
    Map<Integer, EventClass> dataSetIdx2EvtClass = new HashMap<>(); //ugly
    DefaultXYDataset eventDataSet = new DefaultXYDataset();
    for (EventClass evtCl : classes.getEventClasses()) {
        double[][] clusterDataSet = new double[][] { new double[evtCl.getEvents().size()],
                new double[evtCl.getEvents().size()] };
        int i = 0;
        for (Event data : evtCl.getEvents()) {
            clusterDataSet[0][i] = 0;/*ww  w  . jav a  2s .  c o  m*/
            clusterDataSet[1][i] = data.getFeature().getData();
            i++;
        }
        eventDataSet.addSeries("Class " + evtCl.getClassId(), clusterDataSet);

        dataSetIdx2EvtClass.put(dataSetIndex, evtCl);
        dataSetIndex++;
    }
    clusterPlot.setDataset(eventDataSet);

    for (Entry<Integer, EventClass> ent : dataSetIdx2EvtClass.entrySet()) {
        int idx = ent.getKey();
        Color clr = clusterColors.get(ent.getValue());
        logger.info("Setting color " + clr + " for event class " + ent.getValue().getClassId() + " with index "
                + idx);
        clusterPlot.getRendererForDataset(clusterPlot.getDataset(0)).setSeriesPaint(idx, clr);
    }

    clustersDataChart.pack();
    RefineryUtilities.centerFrameOnScreen(clustersDataChart);
    clustersDataChart.setVisible(true);
}

From source file:LoggerGUI.DataLogger.java

public DataLogger(String title) {
    super(title);
    initialize();//from   w  ww.  j a v  a 2  s .c  o m

    final CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new DateAxis("Time"));
    this.datasets = new TimeSeriesCollection[INPUT_COUNT];

    this.lastValue[0] = 100.0;
    this.lastValue[1] = 100.0;
    this.lastValue[2] = 100.0;
    this.lastValue[3] = 100.0;
       
        
        
       
        
    final TimeSeries s0 = new TimeSeries("A0", Millisecond.class);
    final TimeSeries s1 = new TimeSeries("A1", Millisecond.class);
    final TimeSeries s2 = new TimeSeries("A2", Millisecond.class);
    final TimeSeries s3 = new TimeSeries("A3", Millisecond.class);
        
        
        
    this.datasets[0] = new TimeSeriesCollection(s0);
    this.datasets[1] = new TimeSeriesCollection(s1);
    this.datasets[2] = new TimeSeriesCollection(s2);
    this.datasets[3] = new TimeSeriesCollection(s3);
       
        

    final NumberAxis rangeAxis = new NumberAxis("ADC Signal");

    rangeAxis.setAutoRangeIncludesZero(false);
    XYPlot subplot;

        
    XYLineAndShapeRenderer renderer =  new XYLineAndShapeRenderer(true,false);
    XYLineAndShapeRenderer renderer1 = new XYLineAndShapeRenderer(true,false);
    XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(true,false);
    XYLineAndShapeRenderer renderer3 = new XYLineAndShapeRenderer(true,false);
        
    subplot= new XYPlot(
            new TimeSeriesCollection(), null, rangeAxis, new XYLineAndShapeRenderer(true,false)
    );
       
    plot.add(subplot);
       
        
        
    renderer.setBaseShapesVisible(false);
    renderer.setSeriesPaint(0, Color.red);
    subplot.setDataset(0,datasets[0]);
    subplot.setRenderer(0,renderer);
        
        
    renderer1.setBaseShapesVisible(false);
    renderer1.setSeriesPaint(0, Color.blue);
    subplot.setDataset(1,datasets[1]);
    subplot.setRenderer(1,renderer1);
        
        
    renderer2.setBaseShapesVisible(false);
    renderer2.setSeriesPaint(0, Color.black);
    subplot.setDataset(2,datasets[2]);
    subplot.setRenderer(2,renderer2);
        
    subplot.getRendererForDataset(subplot.getDataset(0)).setSeriesPaint(0, Color.red); 
    subplot.getRendererForDataset(subplot.getDataset(1)).setSeriesPaint(1, Color.blue);
    subplot.getRendererForDataset(subplot.getDataset(2)).setSeriesPaint(2, Color.black);
        
    renderer3.setBaseShapesVisible(false);
    renderer3.setSeriesPaint(0, Color.green);
    subplot.setDataset(3,datasets[3]);
    subplot.setRenderer(3,renderer3);
        
        
        
    final JFreeChart chart = new JFreeChart("Data Logger", plot);
    chart.setBorderPaint(Color.black);
    chart.setBorderVisible(true);
    chart.setBackgroundPaint(Color.white);
        
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    final ValueAxis axis = plot.getDomainAxis();
    axis.setAutoRange(true);
    axis.setFixedAutoRange(20000.0);  // 60 seconds

    
    final JPanel content = new JPanel(new BorderLayout());

    final ChartPanel chartPanel = new ChartPanel(chart);
    content.add(chartPanel);

    final JPanel buttonPanel = new JPanel(new FlowLayout());
        
    content.add(buttonPanel, BorderLayout.NORTH);
    chartPanel.setPreferredSize(new java.awt.Dimension(600, 600));
    chartPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    setContentPane(content);
        
        
}

From source file:msi.gama.outputs.layers.ChartLayerStatement.java

/**
 * @throws GamaRuntimeException//from   w  w  w .  j a v  a 2  s.c o  m
 * @param scope
 * @param cycle
 */
private void computeSeries(final IScope scope, final long cycle) throws GamaRuntimeException {
    if (datas.isEmpty()) {
        return;
    }
    List x = new ArrayList();
    Object obj = datas.get(0).getValue(scope);
    if (type == SERIES_CHART && scope.getAgentScope() instanceof BatchAgent) {
        // if (BatchAgent.class.isAssignableFrom(scope.getClass()))
        obj = ((BatchAgent) scope.getAgentScope()).getRunNumber();
    }

    boolean cumulative = false;
    if (obj instanceof GamaList) {
        x = (GamaList) obj;
    } else {
        x.add(obj);
    }
    for (int i = 0; i < x.size(); i++) {
        history.append(x.get(i));
        history.append(',');
    }
    if (!(type == SERIES_CHART & datas.size() < 2)) {
        for (int i = 0; i < datas.size(); i++) {
            if (!datasfromlists.contains(datas.get(i))) {
                if (type == SERIES_CHART & i == 0) {
                    i++;
                }
                XYPlot plot = (XYPlot) chart.getPlot();
                // DefaultTableXYDataset data = (DefaultTableXYDataset) plot.getDataset(i);
                XYDataset data = plot.getDataset(i);
                XYSeries serie = new XYSeries(0, false, false);
                if (type == SERIES_CHART || type == XY_CHART) {
                    serie = ((DefaultTableXYDataset) data).getSeries(0);
                }
                if (type == SCATTER_CHART) {
                    serie = ((XYSeriesCollection) data).getSeries(0);
                }
                List n = new ArrayList();
                Object o = datas.get(i).getValue(scope);
                if (o instanceof GamaList) {
                    n = (GamaList) o;
                } else {
                    cumulative = true;
                    n.add(o);
                }
                if (!cumulative) {
                    if (type == SERIES_CHART || type == XY_CHART) {
                        final XYSeries nserie = new XYSeries(serie.getKey(), false, false);
                        ((DefaultTableXYDataset) data).removeSeries(0);
                        ((DefaultTableXYDataset) data).addSeries(nserie);
                        serie = nserie;
                        // serie.clear();
                    }
                    if (type == SCATTER_CHART) {
                        final XYSeries nserie = new XYSeries(serie.getKey(), false, true);
                        ((XYSeriesCollection) data).removeSeries(0);
                        ((XYSeriesCollection) data).addSeries(nserie);
                        serie = nserie;
                        // serie.clear();
                    }

                }
                // java.lang.System.out.println("gr"+n);
                for (int j = 0; j < n.size(); j++) {
                    if (type == SERIES_CHART) {
                        double d2 = Cast.asFloat(scope, n.get(j));
                        double d1;
                        if (cumulative) {
                            d1 = Cast.asFloat(scope, x.get(j));
                        } else {
                            d1 = Cast.asFloat(scope, j);
                        }
                        serie.addOrUpdate(d1, d2);
                    } else if (type == XY_CHART || type == SCATTER_CHART) {
                        try {
                            IList<Double> list = GamaListType.staticCast(scope, n.get(j), Types.FLOAT, false);
                            double d1 = list.get(0);
                            double d2 = list.get(1);
                            if (cumulative) {
                                serie.addOrUpdate(d1, d2);
                            } else {
                                serie.addOrUpdate(d1, d2);

                            }
                        } catch (IndexOutOfBoundsException e) {
                            // GamaRuntimeException g = GamaRuntimeException.create(e,scope);
                            // g.addContext("each point value should be a gama-point or a 2-float list, value here: "+(Cast.asList(scope, n.get(j))));
                            GamaRuntimeException g = GamaRuntimeException.error(
                                    "each point value should be a gama-point or a 2-float list, value here: "
                                            + Cast.asList(scope, n.get(j)),
                                    scope);
                            GAMA.reportAndThrowIfNeeded(scope, g, true);
                            // TODO Auto-generated catch block
                        }
                    }
                    history.append(n.get(j));
                    history.append(',');
                }
            }
        }
    }
    history.deleteCharAt(history.length() - 1);
    history.append(Strings.LN);

}

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.JFreeChartPlotEngine.java

private void pushDataAndRendererIntoPlot(XYPlot plot, int rangeAxisIdx, XYItemRenderer renderer,
        XYDataset dataset) throws ChartPlottimeException {
    if (dataset != null && renderer != null) {
        int datasetIdx = plot.getDatasetCount();
        if (datasetIdx > 0 && plot.getDataset(datasetIdx - 1) == null) {
            datasetIdx -= 1;/*from   ww  w .  j  a v a 2 s  .co  m*/
        }
        // push dataset and renderer into plot
        try {
            plot.setDataset(datasetIdx, dataset); // if Eclipse states that
            // dataset might not be
            // initialized, you did
            // not consider all
            // possibilities in the
            // condition block above
        } catch (RuntimeException e) {
            // probably this is because the domain axis contains values less
            // then zero and the scaling is logarithmic.
            // The shitty JFreeChart implementation does not throw a proper
            // exception stating what happened,
            // but just a RuntimeException with a string, so this is our
            // best guess:
            if (isProbablyZeroValuesOnLogScaleException(e)) {
                throw new ChartPlottimeException("gui.plotter.error.log_axis_contains_zero", "domain axis");
            } else {
                throw e;
            }
        }
        plot.mapDatasetToRangeAxis(datasetIdx, rangeAxisIdx);
        plot.setRenderer(datasetIdx, renderer);
    } else {
        ChartPlottimeException chartPlottimeException = new ChartPlottimeException(
                new PlotConfigurationError("generic_plotter_error"));
        throw chartPlottimeException;
    }
}

From source file:de.bund.bfr.knime.pmm.common.chart.ChartCreator.java

private void plotDataSet(XYPlot plot, Plotable plotable, String id, Color defaultColor, Shape defaultShape)
        throws ConvertException {
    double[][] points = plotable.getPoints(paramX, paramY, unitX, unitY, transformX, transformY);
    String legend = shortLegend.get(id);
    Color color = colors.get(id);
    Shape shape = shapes.get(id);

    if (addInfoInLegend) {
        legend = longLegend.get(id);/*w  ww .j  a  v  a 2s.  co  m*/
    }

    if (color == null) {
        color = defaultColor;
    }

    if (shape == null) {
        shape = defaultShape;
    }

    if (points != null) {
        DefaultXYDataset dataset = new DefaultXYDataset();
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(drawLines, true);

        dataset.addSeries(legend, points);
        renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
        renderer.setSeriesPaint(0, color);
        renderer.setSeriesShape(0, shape);

        int i;

        if (plot.getDataset(0) == null) {
            i = 0;
        } else {
            i = plot.getDatasetCount();
        }

        plot.setDataset(i, dataset);
        plot.setRenderer(i, renderer);
    }
}