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

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

Introduction

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

Prototype

public XYItemRenderer getRendererForDataset(XYDataset dataset) 

Source Link

Document

Returns the renderer for the specified dataset (this is either the renderer with the same index as the dataset or, if there isn't a renderer with the same index, the default renderer).

Usage

From source file:net.sourceforge.subsonic.controller.StatusChartController.java

public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String type = request.getParameter("type");
    int index = Integer.parseInt(request.getParameter("index"));

    List<TransferStatus> statuses = Collections.emptyList();
    if ("stream".equals(type)) {
        statuses = statusService.getAllStreamStatuses();
    } else if ("download".equals(type)) {
        statuses = statusService.getAllDownloadStatuses();
    } else if ("upload".equals(type)) {
        statuses = statusService.getAllUploadStatuses();
    }//from   w w  w. j  a  v  a2  s.c  om

    if (index < 0 || index >= statuses.size()) {
        return null;
    }
    TransferStatus status = statuses.get(index);

    TimeSeries series = new TimeSeries("Kbps", Millisecond.class);
    TransferStatus.SampleHistory history = status.getHistory();
    long to = System.currentTimeMillis();
    long from = to - status.getHistoryLengthMillis();
    Range range = new DateRange(from, to);

    if (!history.isEmpty()) {

        TransferStatus.Sample previous = history.get(0);

        for (int i = 1; i < history.size(); i++) {
            TransferStatus.Sample sample = history.get(i);

            long elapsedTimeMilis = sample.getTimestamp() - previous.getTimestamp();
            long bytesStreamed = Math.max(0L, sample.getBytesTransfered() - previous.getBytesTransfered());

            double kbps = (8.0 * bytesStreamed / 1024.0) / (elapsedTimeMilis / 1000.0);
            series.addOrUpdate(new Millisecond(new Date(sample.getTimestamp())), kbps);

            previous = sample;
        }
    }

    // Compute moving average.
    series = MovingAverage.createMovingAverage(series, "Kbps", 20000, 5000);

    // Find min and max values.
    double min = 100;
    double max = 250;
    for (Object obj : series.getItems()) {
        TimeSeriesDataItem item = (TimeSeriesDataItem) obj;
        double value = item.getValue().doubleValue();
        if (item.getPeriod().getFirstMillisecond() > from) {
            min = Math.min(min, value);
            max = Math.max(max, value);
        }
    }

    // Add 10% to max value.
    max *= 1.1D;

    // Subtract 10% from min value.
    min *= 0.9D;

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);
    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false);
    XYPlot plot = (XYPlot) chart.getPlot();

    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
    Paint background = new GradientPaint(0, 0, Color.lightGray, 0, IMAGE_HEIGHT, Color.white);
    plot.setBackgroundPaint(background);

    XYItemRenderer renderer = plot.getRendererForDataset(dataset);
    renderer.setSeriesPaint(0, Color.blue.darker());
    renderer.setSeriesStroke(0, new BasicStroke(2f));

    // Set theme-specific colors.
    Color bgColor = getBackground(request);
    Color fgColor = getForeground(request);

    chart.setBackgroundPaint(bgColor);

    ValueAxis domainAxis = plot.getDomainAxis();
    domainAxis.setRange(range);
    domainAxis.setTickLabelPaint(fgColor);
    domainAxis.setTickMarkPaint(fgColor);
    domainAxis.setAxisLinePaint(fgColor);

    ValueAxis rangeAxis = plot.getRangeAxis();
    rangeAxis.setRange(new Range(min, max));
    rangeAxis.setTickLabelPaint(fgColor);
    rangeAxis.setTickMarkPaint(fgColor);
    rangeAxis.setAxisLinePaint(fgColor);

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, IMAGE_HEIGHT);

    return null;
}

From source file:org.madsonic.controller.StatusChartController.java

public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String type = request.getParameter("type");
    int index = Integer.parseInt(request.getParameter("index"));

    List<TransferStatus> statuses = Collections.emptyList();
    if ("stream".equals(type)) {
        statuses = statusService.getAllStreamStatuses();
    } else if ("download".equals(type)) {
        statuses = statusService.getAllDownloadStatuses();
    } else if ("upload".equals(type)) {
        statuses = statusService.getAllUploadStatuses();
    }/*from w w w  . j av a 2 s .  c o m*/

    if (index < 0 || index >= statuses.size()) {
        return null;
    }
    TransferStatus status = statuses.get(index);

    TimeSeries series = new TimeSeries("Kbps", Millisecond.class);
    TransferStatus.SampleHistory history = status.getHistory();
    long to = System.currentTimeMillis();
    long from = to - status.getHistoryLengthMillis();
    Range range = new DateRange(from, to);

    if (!history.isEmpty()) {

        TransferStatus.Sample previous = history.get(0);

        for (int i = 1; i < history.size(); i++) {
            TransferStatus.Sample sample = history.get(i);

            long elapsedTimeMilis = sample.getTimestamp() - previous.getTimestamp();
            long bytesStreamed = Math.max(0L, sample.getBytesTransfered() - previous.getBytesTransfered());

            double kbps = (8.0 * bytesStreamed / 1024.0) / (elapsedTimeMilis / 1000.0);
            series.addOrUpdate(new Millisecond(new Date(sample.getTimestamp())), kbps);

            previous = sample;
        }
    }

    // Compute moving average.
    series = MovingAverage.createMovingAverage(series, "Kbps", 20000, 5000);

    // Find min and max values.
    double min = 100;
    double max = 250;
    for (Object obj : series.getItems()) {
        TimeSeriesDataItem item = (TimeSeriesDataItem) obj;
        double value = item.getValue().doubleValue();
        if (item.getPeriod().getFirstMillisecond() > from) {
            min = Math.min(min, value);
            max = Math.max(max, value);
        }
    }

    // Add 10% to max value.
    max *= 1.1D;

    // Subtract 10% from min value.
    min *= 0.9D;

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);
    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false);
    XYPlot plot = (XYPlot) chart.getPlot();

    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
    Paint background = new GradientPaint(0, 0, Color.lightGray, 0, IMAGE_HEIGHT, Color.white);
    plot.setBackgroundPaint(background);

    XYItemRenderer renderer = plot.getRendererForDataset(dataset);
    renderer.setSeriesPaint(0, Color.gray.darker());
    renderer.setSeriesStroke(0, new BasicStroke(2f));

    // Set theme-specific colors.
    Color bgColor = getBackground(request);
    Color fgColor = getForeground(request);

    chart.setBackgroundPaint(bgColor);

    ValueAxis domainAxis = plot.getDomainAxis();
    domainAxis.setRange(range);
    domainAxis.setTickLabelPaint(fgColor);
    domainAxis.setTickMarkPaint(fgColor);
    domainAxis.setAxisLinePaint(fgColor);

    ValueAxis rangeAxis = plot.getRangeAxis();
    rangeAxis.setRange(new Range(min, max));
    rangeAxis.setTickLabelPaint(fgColor);
    rangeAxis.setTickMarkPaint(fgColor);
    rangeAxis.setAxisLinePaint(fgColor);

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, IMAGE_HEIGHT);

    return null;
}

From source file:net.sf.maltcms.chromaui.charts.events.ChartPanelMouseListener.java

/**
 *
 * @param arg0/*from ww  w  .  j a v  a  2s .  c  o m*/
 */

@Override
public void chartMouseClicked(final ChartMouseEvent arg0) {
    final ChartPanelMouseListener cpml = this;
    if (arg0.getEntity() != null) {
        if (arg0.getEntity() instanceof XYItemEntity) {
            XYItemEntity xyie = (XYItemEntity) arg0.getEntity();

            if (arg0.getTrigger().getButton() == MouseEvent.BUTTON1) {
                //                
                if (arg0.getTrigger().isAltDown() && arg0.getTrigger().isShiftDown()) {
                    //                        System.out.println("Item removed");
                    fireEvent(new XYItemEntityRemovedEvent((XYItemEntity) arg0.getEntity(), cpml));
                } else if (arg0.getTrigger().isAltDown()) {
                    //                        System.out.println("Item added");
                    fireEvent(new XYItemEntityAddedEvent((XYItemEntity) arg0.getEntity(), cpml));
                } else {
                    setTarget(arg0);
                    //                        System.out.println("Item clicked");
                    fireEvent(new XYItemEntityClickedEvent((XYItemEntity) arg0.getEntity(), cpml));
                }
            }
        } else if (arg0.getEntity() instanceof LegendItemEntity) {
            JPopupMenu jpm = new JPopupMenu();
            final LegendItemEntity lie = (LegendItemEntity) arg0.getEntity();
            Dataset ds = lie.getDataset();
            Comparable skey = lie.getSeriesKey();
            Plot plot = arg0.getChart().getPlot();
            if (plot instanceof XYPlot) {
                XYPlot xyplot = arg0.getChart().getXYPlot();
                if (xyplot.getSeriesCount() > 1) {
                    XYDataset xyds = (XYDataset) ds;
                    XYItemRenderer xyir = xyplot.getRendererForDataset(xyds);

                    xyir.setSeriesVisible(xyds.indexOf(skey), !xyir.isSeriesVisible(xyds.indexOf(skey)));
                    xyir.setSeriesVisibleInLegend(xyds.indexOf(skey), Boolean.TRUE);
                }
            } else if (plot instanceof CategoryPlot) {
                CategoryPlot cplot = arg0.getChart().getCategoryPlot();
                if (cplot.getDatasetCount() > 1) {
                    CategoryDataset cds = (CategoryDataset) ds;
                    CategoryItemRenderer xyir = cplot.getRendererForDataset(cds);
                    int seriesIndex = cds.getColumnIndex(skey);
                    if (seriesIndex == -1) {
                        seriesIndex = cds.getRowIndex(skey);
                    }
                    xyir.setSeriesVisible(seriesIndex, !xyir.isSeriesVisible(seriesIndex));
                    xyir.setSeriesVisibleInLegend(seriesIndex, Boolean.TRUE);
                }
            }
            //                AbstractAction hse = new AbstractAction("Hide") {
            //
            //                    @Override
            //                    public void actionPerformed(ActionEvent ae) {
            //                        
            //                    }
            //                };
            //                AbstractAction hse = new AbstractAction("Show") {
            //
            //                    @Override
            //                    public void actionPerformed(ActionEvent ae) {
            //                        
            //                    }
            //                };
            //                AbstractAction hse = new AbstractAction("Remove") {
            //
            //                    @Override
            //                    public void actionPerformed(ActionEvent ae) {
            //                        
            //                    }
            //                };
        }
    }
}

From source file:com.signalcollect.sna.gephiconnectors.SignalCollectGephiConnector.java

/**
 * Creates the Chart of the Degree Distribution according to the calculated
 * distribution//from   w  w  w.j a  v  a  2  s. com
 * 
 * @param degreeDistribution
 * @return a {@link JFreeChart} containing the distribution of degrees in
 *         the graph
 * @throws IOException
 */
public JFreeChart createDegreeDistributionChart(Map<Integer, Integer> degreeDistribution) throws IOException {
    XYSeries dSeries = new XYSeries("number of occurences");
    for (Iterator it = degreeDistribution.entrySet().iterator(); it.hasNext();) {
        Map.Entry d = (Map.Entry) it.next();
        Number x = (Number) d.getKey();
        Number y = (Number) d.getValue();
        dSeries.add(x, y);
    }
    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(dSeries);
    dataset.setAutoWidth(true);

    JFreeChart chart = ChartFactory.createHistogram("Degree Distribution", "Degree centrality value",
            "number of occurences", dataset, PlotOrientation.VERTICAL, true, true, true);

    XYPlot plot = chart.getXYPlot();
    XYBarRenderer renderer0 = new XYBarRenderer();
    Font font = new Font("Font", 0, 14);
    renderer0.setMargin(0.2);
    renderer0.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
    renderer0.setBaseItemLabelsVisible(true);
    renderer0.setBaseItemLabelFont(font);
    plot.setDataset(0, dataset);
    plot.setRenderer(0, renderer0);
    plot.getRendererForDataset(plot.getDataset(0)).setSeriesPaint(0, Color.BLUE);
    return chart;
}

From source file:com.signalcollect.sna.gephiconnectors.SignalCollectGephiConnector.java

/**
 * Creates the Chart of the Clustering Distribution according to the
 * calculated distribution//  w  ww .  ja  va  2s. c o  m
 * 
 * @param clusterDistribution
 * @return a {@link JFreeChart} containing the distribution of local cluster
 *         coefficients in the graph
 * @throws IOException
 */
public JFreeChart createClusterDistributionChart(Map<Double, Integer> clusterDistribution) throws IOException {
    XYSeries dSeries = new XYSeries("number of occurences");
    for (Iterator it = clusterDistribution.entrySet().iterator(); it.hasNext();) {
        Map.Entry d = (Map.Entry) it.next();
        Number x = (Number) d.getKey();
        Number y = (Number) d.getValue();
        dSeries.add(x, y);
    }
    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(dSeries);
    dataset.setAutoWidth(true);

    JFreeChart chart = ChartFactory.createHistogram("Local Cluster Coefficient Distribution",
            "Local Cluster Coefficient value", "number of occurences", dataset, PlotOrientation.VERTICAL, true,
            true, true);

    XYPlot plot = chart.getXYPlot();
    XYBarRenderer renderer0 = new XYBarRenderer();
    Font font = new Font("Font", 0, 14);
    renderer0.setMargin(0.2);
    renderer0.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
    renderer0.setBaseItemLabelsVisible(true);
    renderer0.setBaseItemLabelFont(font);
    plot.setDataset(0, dataset);
    plot.setRenderer(0, renderer0);

    plot.getRendererForDataset(plot.getDataset(0)).setSeriesPaint(0, Color.BLUE);

    return chart;
}

From source file:net.sf.maltcms.common.charts.ui.XYChartTopComponent.java

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
    final String renderer = (String) jComboBox1.getSelectedItem();
    Task t = RequestProcessor.getDefault().create(new Runnable() {
        @Override//from  ww  w.  j a v  a  2s  . com
        public void run() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    panel.setEnabled(false);
                    panel.invalidate();
                    panel.validate();
                }
            });

            int nrenderer = panel.getChart().getXYPlot().getRendererCount();
            XYPlot plot = panel.getChart().getXYPlot();
            int ndatasets = panel.getChart().getXYPlot().getDatasetCount();
            List<Shape> shapes = new LinkedList<>();
            for (int i = 0; i < nrenderer; i++) {
                for (int j = 0; j < plot.getDataset(i).getSeriesCount(); j++) {
                    XYDataset d = plot.getDataset(i);
                    for (int k = 0; k < d.getSeriesCount(); k++) {
                        Shape s = plot.getRendererForDataset(d).getSeriesShape(k);
                        shapes.add(s);
                    }
                }
            }
            switch (renderer) {
            case "Line And Shape":
                panel.getChart().getXYPlot().setRenderer(new XYLineAndShapeRenderer(true, true));
                break;
            case "Line":
                panel.getChart().getXYPlot().setRenderer(new XYLineAndShapeRenderer(true, false));
                break;
            case "Shape":
                panel.getChart().getXYPlot().setRenderer(new XYLineAndShapeRenderer(false, true));
                break;
            case "Area":
                panel.getChart().getXYPlot().setRenderer(new XYAreaRenderer(XYAreaRenderer.AREA));
                break;
            case "Area w/ Shapes":
                panel.getChart().getXYPlot().setRenderer(new XYAreaRenderer(XYAreaRenderer.AREA_AND_SHAPES));
                break;
            }
            panel.getChart().getXYPlot().getRenderer().setBaseToolTipGenerator(new StandardXYToolTipGenerator(
                    "%2.5f", NumberFormat.getNumberInstance(), NumberFormat.getNumberInstance()));
            int shapeIndex = 0;
            for (int i = 0; i < nrenderer; i++) {
                for (int j = 0; j < plot.getDataset(i).getSeriesCount(); j++) {
                    XYDataset d = plot.getDataset(i);
                    for (int k = 0; k < d.getSeriesCount(); k++) {
                        plot.getRendererForDataset(d).setSeriesShape(k, shapes.get(shapeIndex));
                        shapeIndex++;
                    }
                }
            }
            customizeChart(panel);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    panel.setEnabled(true);
                    panel.invalidate();
                    panel.validate();
                }
            });

        }
    });
    t.addTaskListener(new XYChartLoaderTaskListener());
    RequestProcessor.getDefault().post(t);
}

From source file:com.diversityarrays.kdxplore.scatterplot.ScatterPlotPanel.java

private void generateChart(boolean recreateDataSet, Bag<String> missingOrBad, Bag<String> suppressed) {

    if (recreateDataSet) {
        currentDataSet = createSampleDataSet(missingOrBad, suppressed);
    }//from w  w  w .java  2s .c om

    XYSeriesCollection dataset = currentDataSet;

    PlotOrientation orientation = PlotOrientation.VERTICAL;
    boolean show = true;
    boolean toolTips = true;
    boolean urls = true;

    chart = ChartFactory.createScatterPlot(getTitle(), xAxisName, yAxisName, dataset, orientation, show,
            toolTips, urls);

    if (DEBUG) {
        System.out.println("Generated new ScatterPlot"); //$NON-NLS-1$
    }

    TraitColorProvider traitColorProvider = colorProviderFactory.get();

    XYPlot xyPlot = (XYPlot) chart.getPlot();
    XYItemRenderer xyr = xyPlot.getRendererForDataset(dataset);

    boolean anyDisplayValues = false;
    if (!xNumberToTraitValue.numberToTraitValue.isEmpty()) {
        anyDisplayValues = true;
    } else {
        for (NumberToTraitValue n2tv : numberToTraitValueBySeriesIndex.values()) {
            if (!n2tv.numberToTraitValue.isEmpty()) {
                anyDisplayValues = true;
                break;
            }
        }
    }
    if (anyDisplayValues) {
        xyr.setBaseToolTipGenerator(new MyXYToolTipGenerator());
    }

    for (TraitInstance ti : traitInstances) {
        ColorPair colorPair = traitColorProvider.getTraitInstanceColor(ti);
        if (colorPair != null) {
            if (DEBUG) {
                System.out.println("Got a color back for: " + InstanceIdentifierUtil.getInstanceIdentifier(ti)); //$NON-NLS-1$
            }

            String validName = traitNameStyle.makeTraitInstanceName(ti);
            if (seriesCountByTraitName.get(validName) != null) {
                xyr.setSeriesPaint(seriesCountByTraitName.get(validName), colorPair.getBackground());
            }
        }
    }
    xyPlot.setRenderer(xyr);

    chartPanel.setChart(chart);

    dataxMin = xyPlot.getDomainAxis().getLowerBound();
    dataxMax = xyPlot.getDomainAxis().getUpperBound();

    datayMin = xyPlot.getRangeAxis().getLowerBound();
    datayMax = xyPlot.getRangeAxis().getUpperBound();
}

From source file:org.trade.ui.chart.CandlestickChart.java

/**
 * Method createChart./*from   w w w  .ja v  a  2  s  .  c  o m*/
 * 
 * @param strategyData
 *            StrategyData
 * @param title
 *            String
 * @return JFreeChart
 */
private JFreeChart createChart(StrategyData strategyData, String title, Tradingday tradingday) {

    DateAxis dateAxis = new DateAxis("Date");
    dateAxis.setVerticalTickLabels(true);
    dateAxis.setDateFormatOverride(new SimpleDateFormat("dd/MM hh:mm"));
    dateAxis.setTickMarkPosition(DateTickMarkPosition.START);
    NumberAxis priceAxis = new NumberAxis("Price");
    priceAxis.setAutoRange(true);
    priceAxis.setAutoRangeIncludesZero(false);
    XYPlot pricePlot = new XYPlot(strategyData.getCandleDataset(), dateAxis, priceAxis,
            strategyData.getCandleDataset().getRenderer());
    pricePlot.setOrientation(PlotOrientation.VERTICAL);
    pricePlot.setDomainPannable(true);
    pricePlot.setRangePannable(true);
    pricePlot.setDomainCrosshairVisible(true);
    pricePlot.setDomainCrosshairLockedOnData(true);
    pricePlot.setRangeCrosshairVisible(true);
    pricePlot.setRangeCrosshairLockedOnData(true);
    pricePlot.setRangeGridlinePaint(new Color(204, 204, 204));
    pricePlot.setDomainGridlinePaint(new Color(204, 204, 204));
    pricePlot.setBackgroundPaint(Color.white);

    /*
     * Calculate the number of 15min segments in this trading day. i.e.
     * 6.5hrs/15min = 26 and there are a total of 96 = one day
     */

    int segments15min = (int) (tradingday.getClose().getTime() - tradingday.getOpen().getTime())
            / (1000 * 60 * 15);

    SegmentedTimeline segmentedTimeline = new SegmentedTimeline(SegmentedTimeline.FIFTEEN_MINUTE_SEGMENT_SIZE,
            segments15min, (96 - segments15min));

    Date startDate = tradingday.getOpen();
    Date endDate = tradingday.getClose();

    if (!strategyData.getCandleDataset().getSeries(0).isEmpty()) {
        startDate = ((CandleItem) strategyData.getCandleDataset().getSeries(0).getDataItem(0)).getPeriod()
                .getStart();
        startDate = TradingCalendar.getSpecificTime(tradingday.getOpen(), startDate);
        endDate = ((CandleItem) strategyData.getCandleDataset().getSeries(0)
                .getDataItem(strategyData.getCandleDataset().getSeries(0).getItemCount() - 1)).getPeriod()
                        .getStart();
        endDate = TradingCalendar.getSpecificTime(tradingday.getClose(), endDate);
    }

    segmentedTimeline.setStartTime(startDate.getTime());
    segmentedTimeline.addExceptions(getNonTradingPeriods(startDate, endDate, tradingday.getOpen(),
            tradingday.getClose(), segmentedTimeline));
    dateAxis.setTimeline(segmentedTimeline);

    // Build Combined Plot
    CombinedDomainXYPlot mainPlot = new CombinedDomainXYPlot(dateAxis);
    mainPlot.add(pricePlot, 4);

    int axixIndex = 0;
    int datasetIndex = 0;

    /*
     * Change the List of indicators so that the candle dataset is the first
     * one in the list. The main chart must be plotted first.
     */
    List<IndicatorDataset> indicators = new ArrayList<IndicatorDataset>(0);
    for (IndicatorDataset item : strategyData.getIndicators()) {
        if (IndicatorSeries.CandleSeries.equals(item.getType(0))) {
            indicators.add(item);
        }
    }
    for (IndicatorDataset item : strategyData.getIndicators()) {
        if (!IndicatorSeries.CandleSeries.equals(item.getType(0))) {
            indicators.add(item);
        }
    }
    for (int i = 0; i < indicators.size(); i++) {
        IndicatorDataset indicator = indicators.get(i);
        if (indicator.getDisplaySeries(0)) {

            if (indicator.getSubChart(0)) {
                String axisName = "Price";
                if (IndicatorSeries.CandleSeries.equals(indicator.getType(0))) {
                    axisName = ((CandleSeries) indicator.getSeries(0)).getSymbol();
                } else {
                    org.trade.dictionary.valuetype.IndicatorSeries code = org.trade.dictionary.valuetype.IndicatorSeries
                            .newInstance(indicator.getType(0));
                    axisName = code.getDisplayName();
                }
                NumberAxis subPlotAxis = new NumberAxis(axisName);
                subPlotAxis.setAutoRange(true);
                subPlotAxis.setAutoRangeIncludesZero(false);

                XYPlot subPlot = new XYPlot((XYDataset) indicator, dateAxis, subPlotAxis,
                        indicator.getRenderer());

                subPlot.setOrientation(PlotOrientation.VERTICAL);
                subPlot.setDomainPannable(true);
                subPlot.setRangePannable(true);
                subPlot.setDomainCrosshairVisible(true);
                subPlot.setDomainCrosshairLockedOnData(true);
                subPlot.setRangeCrosshairVisible(true);
                subPlot.setRangeCrosshairLockedOnData(true);
                subPlot.setRangeGridlinePaint(new Color(204, 204, 204));
                subPlot.setDomainGridlinePaint(new Color(204, 204, 204));
                subPlot.setBackgroundPaint(Color.white);
                XYItemRenderer renderer = subPlot.getRendererForDataset((XYDataset) indicator);
                for (int seriesIndex = 0; seriesIndex < ((XYDataset) indicator)
                        .getSeriesCount(); seriesIndex++) {
                    renderer.setSeriesPaint(seriesIndex, indicator.getSeriesColor(seriesIndex));
                }
                mainPlot.add(subPlot, 1);

            } else {
                datasetIndex++;
                pricePlot.setDataset(datasetIndex, (XYDataset) indicator);
                if (IndicatorSeries.CandleSeries.equals(indicator.getType(0))) {
                    // add secondary axis
                    axixIndex++;

                    final NumberAxis axis2 = new NumberAxis(
                            ((CandleSeries) indicator.getSeries(0)).getSymbol());
                    axis2.setAutoRange(true);
                    axis2.setAutoRangeIncludesZero(false);
                    pricePlot.setRangeAxis(datasetIndex, axis2);
                    pricePlot.setRangeAxisLocation(i + 1, AxisLocation.BOTTOM_OR_RIGHT);
                    pricePlot.mapDatasetToRangeAxis(datasetIndex, axixIndex);
                    pricePlot.setRenderer(datasetIndex, new StandardXYItemRenderer());
                } else {
                    pricePlot.setRenderer(datasetIndex, indicator.getRenderer());
                }
                XYItemRenderer renderer = pricePlot.getRendererForDataset((XYDataset) indicator);

                for (int seriesIndex = 0; seriesIndex < ((XYDataset) indicator)
                        .getSeriesCount(); seriesIndex++) {
                    renderer.setSeriesPaint(seriesIndex, indicator.getSeriesColor(seriesIndex));
                }
            }
        }
    }
    JFreeChart jfreechart = new JFreeChart(title, null, mainPlot, true);
    jfreechart.setAntiAlias(false);
    return jfreechart;
}

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;/*w  w  w .j  av a2 s . com*/
            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:osh.comdriver.simulation.cruisecontrol.ScheduleDrawer.java

/**
 * Creates a chart./*from  w w  w. jav a2  s  .  c  o m*/
 *
 * @param dataset1  a dataset.
 * @return A chart.
 */
private static JFreeChart createChart(XYDataset dataset1, //power
        XYDataset dataset2, //costs
        XYDataset dataset3, long time) {

    JFreeChart chart = ChartFactory.createTimeSeriesChart("schedule", // title
            "time", // x-axis label
            "power", // y-axis label
            dataset1, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );

    chart.setBackgroundPaint(Color.white);

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

    NumberAxis axis1 = new NumberAxis("power");
    NumberAxis axis2 = new NumberAxis("costs");
    axis1.setAutoRangeIncludesZero(true);
    axis1.setUpperBound(5000);
    axis1.setLowerBound(-5000);
    axis2.setAutoRangeIncludesZero(true);
    axis2.setUpperBound(50);
    axis2.setLowerBound(0);
    plot.setRangeAxis(0, axis1);
    plot.setRangeAxis(1, axis2);

    plot.setDataset(1, dataset2);
    plot.mapDatasetToRangeAxis(1, 1);

    plot.setDataset(2, dataset3);
    plot.mapDatasetToRangeAxis(2, 0);

    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);
    //TODO: SHADOWS OFF

    final StandardXYItemRenderer r1 = new StandardXYItemRenderer();
    final StandardXYItemRenderer r2 = new StandardXYItemRenderer();
    final StandardXYItemRenderer r3 = new StandardXYItemRenderer();
    final StandardXYItemRenderer r4 = new StandardXYItemRenderer();
    plot.setRenderer(0, r1);
    plot.setRenderer(1, r2);
    plot.setRenderer(2, r3);
    plot.setRenderer(3, r4);

    int numberOfSeries = 0;
    numberOfSeries += dataset1.getSeriesCount();
    numberOfSeries += dataset2.getSeriesCount();
    numberOfSeries += dataset3.getSeriesCount();

    Color[] color = new Color[numberOfSeries];

    for (int i = 0; i < numberOfSeries / 2; i++) {
        color[i] = Color.getHSBColor(i * 1.0f / (numberOfSeries / 2), 1.0f, 1.0f);
    }

    int i = 0;

    for (int j = 0; j < dataset1.getSeriesCount() / 2; j++) {
        float[] rgbcolor = Color.RGBtoHSB(color[i].getRed(), color[i].getGreen(), color[i].getBlue(), null);
        plot.getRendererForDataset(dataset1).setSeriesPaint(2 * j, Color.getHSBColor(rgbcolor[0], 1.0f, 1.0f));
        plot.getRendererForDataset(dataset1).setSeriesPaint(2 * j + 1,
                Color.getHSBColor(rgbcolor[0], 1.0f, 0.6f));
        i++;
    }
    for (int j = 0; j < dataset2.getSeriesCount() / 2; j++) {
        float[] rgbcolor = Color.RGBtoHSB(color[i].getRed(), color[i].getGreen(), color[i].getBlue(), null);
        plot.getRendererForDataset(dataset2).setSeriesPaint(2 * j, Color.getHSBColor(rgbcolor[0], 1.0f, 1.0f));
        plot.getRendererForDataset(dataset2).setSeriesPaint(2 * j + 1,
                Color.getHSBColor(rgbcolor[0], 1.0f, 0.6f));
        i++;
    }
    for (int j = 0; j < dataset3.getSeriesCount() / 2; j++) {
        float[] rgbcolor = Color.RGBtoHSB(color[i].getRed(), color[i].getGreen(), color[i].getBlue(), null);
        plot.getRendererForDataset(dataset3).setSeriesPaint(2 * j, Color.getHSBColor(rgbcolor[0], 1.0f, 1.0f));
        plot.getRendererForDataset(dataset3).setSeriesPaint(2 * j + 1,
                Color.getHSBColor(rgbcolor[0], 1.0f, 0.6f));
        i++;
    }

    // NOW line
    double upperBound = plot.getRangeAxis(1).getUpperBound();
    double lowerBound = plot.getRangeAxis(1).getLowerBound();

    XYSeries nowLine = new XYSeries("now");
    nowLine.add(time * 1000, lowerBound);
    nowLine.add(time * 1000, upperBound);
    XYSeriesCollection nowColl = new XYSeriesCollection(); //power axis
    nowColl.addSeries(nowLine);
    XYDataset nowSet = nowColl;

    plot.setDataset(3, nowSet);
    plot.mapDatasetToRangeAxis(3, 1);

    plot.getRendererForDataset(nowSet).setSeriesPaint(0, Color.DARK_GRAY);
    plot.getRendererForDataset(nowSet).setSeriesStroke(0, (Stroke) new BasicStroke(2.0f, BasicStroke.CAP_ROUND,
            BasicStroke.JOIN_ROUND, 1.0f, new float[] { 6.0f, 6.0f }, 0.0f));

    plot.setDomainAxis(new DateAxis());
    plot.getDomainAxis().setAutoRange(false);

    long begin = (time / 86400) * 86400 * 1000; //beginning of day
    long end = begin + 86400 * 2 * 1000;

    plot.getDomainAxis().setRange(begin, end);

    return chart;

}