Example usage for org.jfree.chart.axis DateAxis DateAxis

List of usage examples for org.jfree.chart.axis DateAxis DateAxis

Introduction

In this page you can find the example usage for org.jfree.chart.axis DateAxis DateAxis.

Prototype

public DateAxis(String label) 

Source Link

Document

Creates a date axis with the specified label.

Usage

From source file:AtomPanel.java

private void initJFreeChart() {
    this.numOfStream = numOfStream;

    datasets = new TimeSeriesCollection();
    trend = new TimeSeriesCollection();
    projpcs = new TimeSeriesCollection();
    spe = new TimeSeriesCollection();

    for (int i = 0; i < MaxNumOfStream; i++) {
        //add streams
        TimeSeries timeseries = new TimeSeries("Stream " + i, Millisecond.class);
        datasets.addSeries(timeseries);/*from   w w  w  .j av  a 2 s. c o m*/
        timeseries.setHistoryCount(historyRange);
        //add trend variables
        TimeSeries trendSeries = new TimeSeries("Trend " + i, Millisecond.class);
        trend.addSeries(trendSeries);
        trendSeries.setHistoryCount(historyRange);
        //add proj onto PCs variables
        TimeSeries PC = new TimeSeries("Projpcs " + i, Millisecond.class);
        projpcs.addSeries(PC);
        PC.setHistoryCount(historyRange);
        //add spe streams
        TimeSeries speSeries = new TimeSeries("Spe " + i, Millisecond.class);
        spe.addSeries(speSeries);
        speSeries.setHistoryCount(historyRange);
    }
    combineddomainxyplot = new CombinedDomainXYPlot(new DateAxis("Time"));
    //data stream  plot
    DateAxis domain = new DateAxis("Time");
    NumberAxis range = new NumberAxis("Streams");
    domain.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    range.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    domain.setLabelFont(new Font("SansSerif", Font.PLAIN, 14));
    range.setLabelFont(new Font("SansSerif", Font.PLAIN, 14));

    XYItemRenderer renderer = new DefaultXYItemRenderer();
    renderer.setItemLabelsVisible(false);
    renderer.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
    XYPlot plot = new XYPlot(datasets, domain, range, renderer);
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
    domain.setAutoRange(true);
    domain.setLowerMargin(0.0);
    domain.setUpperMargin(0.0);
    domain.setTickLabelsVisible(true);

    range.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    combineddomainxyplot.add(plot);

    //Trend captured by pca
    DateAxis domain0 = new DateAxis("Time");
    NumberAxis range0 = new NumberAxis("PCA Trend");
    domain0.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    range0.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    domain0.setLabelFont(new Font("SansSerif", Font.PLAIN, 14));
    range0.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));

    XYItemRenderer renderer0 = new DefaultXYItemRenderer();
    renderer0.setItemLabelsVisible(false);
    renderer0.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
    renderer0.setSeriesPaint(0, Color.blue);
    renderer0.setSeriesPaint(1, Color.red);
    renderer0.setSeriesPaint(2, Color.magenta);
    XYPlot plot0 = new XYPlot(trend, domain0, range0, renderer0);
    plot0.setBackgroundPaint(Color.lightGray);
    plot0.setDomainGridlinePaint(Color.white);
    plot0.setRangeGridlinePaint(Color.white);
    plot0.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
    domain0.setAutoRange(true);
    domain0.setLowerMargin(0.0);
    domain0.setUpperMargin(0.0);
    domain0.setTickLabelsVisible(false);

    range0.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    combineddomainxyplot.add(plot0);

    //proj on PCs plot
    DateAxis domain1 = new DateAxis("Time");
    NumberAxis range1 = new NumberAxis("Proj on PCs");
    domain1.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    range1.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    domain1.setLabelFont(new Font("SansSerif", Font.PLAIN, 14));
    range1.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));

    XYItemRenderer renderer1 = new DefaultXYItemRenderer();
    renderer1.setItemLabelsVisible(false);
    renderer1.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
    renderer1.setSeriesPaint(0, Color.blue);
    renderer1.setSeriesPaint(1, Color.red);
    renderer1.setSeriesPaint(2, Color.magenta);
    plot1 = new XYPlot(projpcs, domain1, range1, renderer1);
    plot1.setBackgroundPaint(Color.lightGray);
    plot1.setDomainGridlinePaint(Color.white);
    plot1.setRangeGridlinePaint(Color.white);
    plot1.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
    domain1.setAutoRange(true);
    domain1.setLowerMargin(0.0);
    domain1.setUpperMargin(0.0);
    domain1.setTickLabelsVisible(false);

    range1.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    combineddomainxyplot.add(plot1);

    //spe  plot
    DateAxis domain2 = new DateAxis("Time");
    NumberAxis range2 = new NumberAxis("SPE");
    domain2.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    range2.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    domain2.setLabelFont(new Font("SansSerif", Font.PLAIN, 14));
    range2.setLabelFont(new Font("SansSerif", Font.PLAIN, 14));

    XYItemRenderer renderer2 = new DefaultXYItemRenderer();
    renderer2.setItemLabelsVisible(false);
    renderer2.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
    XYPlot plot2 = new XYPlot(spe, domain2, range2, renderer);
    plot2.setBackgroundPaint(Color.lightGray);
    plot2.setDomainGridlinePaint(Color.white);
    plot2.setRangeGridlinePaint(Color.white);
    plot2.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
    domain2.setAutoRange(true);
    domain2.setLowerMargin(0.0);
    domain2.setUpperMargin(0.0);
    domain2.setTickLabelsVisible(true);

    range2.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    combineddomainxyplot.add(plot2);

    ValueAxis axis = plot.getDomainAxis();
    axis.setAutoRange(true);
    axis.setFixedAutoRange(historyRange); // 60 seconds
    JFreeChart chart;
    if (this.pcaType == AtomUtils.PCAType.pca)
        chart = new JFreeChart("CloudWatch-ATOM with Exact Data", new Font("SansSerif", Font.BOLD, 18),
                combineddomainxyplot, false);
    else if (this.pcaType == AtomUtils.PCAType.pcaTrack)
        chart = new JFreeChart("CloudWatch-ATOM with Fixed Tracking Threshold",
                new Font("SansSerif", Font.BOLD, 18), combineddomainxyplot, false);
    else
        chart = new JFreeChart("CloudWatch-ATOM with Dynamic Tracking Threshold",
                new Font("SansSerif", Font.BOLD, 18), combineddomainxyplot, false);
    chart.setBackgroundPaint(Color.white);
    ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
            BorderFactory.createLineBorder(Color.black)));
    AtomPanel.this.add(chartPanel, BorderLayout.CENTER);
}

From source file:net.commerce.zocalo.freechart.ChartGenerator.java

public static JFreeChart createCustomXYStepAreaChart(TimePeriodValuesCollection top,
        TimePeriodValuesCollection bottom) {
    DateAxis xAxis = new DateAxis(null);
    NumberAxis yAxis = new NumberAxis("price");
    yAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
    yAxis.setUpperBound(100);/*  w w  w  . j  a v  a  2 s. c o m*/
    yAxis.setLowerBound(0.0);

    XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
    plot.setDataset(0, top);
    plot.setDataset(1, bottom);
    XYStepAreaRenderer bottomRenderer = new XYStepAreaRenderer(XYStepAreaRenderer.AREA, null, null);
    XYStepAreaRenderer topRenderer = new XYStepAreaRenderer(XYStepAreaRenderer.AREA, null, null);
    topRenderer.setRangeBase(1.0);
    topRenderer.setSeriesPaint(0, new Color(204, 255, 153));
    bottomRenderer.setSeriesPaint(0, new Color(51, 255, 204));
    plot.setRenderer(bottomRenderer);
    plot.setRenderer(1, topRenderer);
    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setDomainCrosshairVisible(false);
    plot.setRangeCrosshairVisible(false);
    return new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
}

From source file:jgnash.ui.report.compiled.MonthlyAccountBalanceChartCompare.java

private JFreeChart createVerticalXYBarChart(final Account a, final Account a2) {
    DateFormat df = new SimpleDateFormat("MM/yy");
    TimeSeriesCollection data = createTimeSeriesCollection(a, a2);

    DateAxis dateAxis = new DateAxis(rb.getString("Column.Date"));
    dateAxis.setTickUnit(new DateTickUnit(DateTickUnitType.MONTH, 1, df));
    dateAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);

    // if (a.getTransactionCount() > 0) {
    Date start = DateUtils.asDate(DateUtils.getFirstDayOfTheMonth(startDateField.getLocalDate()));
    Date end = DateUtils.asDate(DateUtils.getLastDayOfTheMonth(endDateField.getLocalDate()));
    dateAxis.setRange(start, end);//from www.  j a v a  2 s .  c om
    // }

    NumberAxis valueAxis = new NumberAxis(
            rb.getString("Column.Balance") + "-" + a.getCurrencyNode().getSymbol());
    StandardXYToolTipGenerator tooltipGenerator = new StandardXYToolTipGenerator("{1}, {2}", df,
            NumberFormat.getNumberInstance());
    ClusteredXYBarRenderer renderer = new ClusteredXYBarRenderer(0.2, false);
    renderer.setBaseToolTipGenerator(tooltipGenerator);

    XYPlot plot = new XYPlot(data, dateAxis, valueAxis, renderer);
    String title;
    if (jcb_compare.isSelected()) {
        title = a.getPathName() + " vs " + a2.getPathName();
    } else {
        title = rb.getString("Title.AccountBalance") + " - " + a.getPathName();
    }

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, false);
    chart.setBackgroundPaint(null);

    return chart;
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.blockcharts.TimeBlockChart.java

@Override
public JFreeChart createChart(DatasetMap datasets) {
    logger.debug("IN");
    super.createChart(datasets);
    DefaultXYZDataset dataset = (DefaultXYZDataset) datasets.getDatasets().get("1");

    DateAxis xAxis = new DateAxis(yLabel);
    xAxis.setLowerMargin(0.0);/*from  ww w  .  j a  va2s  .com*/
    xAxis.setUpperMargin(0.0);
    xAxis.setInverted(false);
    xAxis.setDateFormatOverride(new SimpleDateFormat("dd/MM/yyyy"));
    if (dateAutoRange) {
        xAxis.setAutoRange(true);
    } else {
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        DateTickUnit unit = new DateTickUnit(DateTickUnit.DAY, 1, formatter);
        xAxis.setTickUnit(unit);
    }

    if (dateMin != null && dateMax != null) {
        xAxis.setRange(dateMin, addDay(dateMax));
    } else {
        xAxis.setRange(minDateFound, addDay(maxDateFound));
    }

    //      Calendar c=new GregorianCalendar();
    //      c.set(9 + 2000, Calendar.JANUARY, 1);
    //      java.util.Date minima=c.getTime();
    //      Calendar c1=new GregorianCalendar();
    //      c1.set(9 + 2000, Calendar.FEBRUARY, 1);
    //      java.util.Date massima=c1.getTime();

    NumberAxis yAxis = new NumberAxis(xLabel);
    yAxis.setUpperMargin(0.0);
    yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    yAxis.setRange(hourMin, hourMax);

    XYBlockRenderer renderer = new XYBlockRenderer();
    renderer.setBlockWidth(BLOCK_HEIGHT);
    // one block for each minute!
    renderer.setBlockHeight(0.017);
    //renderer.setBlockWidth(1);
    renderer.setBlockAnchor(RectangleAnchor.BOTTOM_LEFT);

    //      MyXYItemLabelGenerator my=new MyXYItemLabelGenerator();
    //      renderer.setItemLabelsVisible(null);
    //      renderer.setSeriesItemLabelGenerator(0, my);
    //      renderer.setSeriesItemLabelsVisible(0, true);

    //      XYTextAnnotation annotation1 = new XYTextAnnotation(
    //      "P_",1.2309372E12, 14.3);
    //      XYTextAnnotation annotation2 = new XYTextAnnotation(
    //      "P_",1.2308508E12, 16.3);

    for (Iterator iterator = annotations.keySet().iterator(); iterator.hasNext();) {
        String annotationCode = (String) iterator.next();
        AnnotationBlock annotationBlock = annotations.get(annotationCode);
        XYTextAnnotation xyAnnotation = new XYTextAnnotation(annotationBlock.getAnnotation(),
                annotationBlock.getXPosition() + ANNOTATION_HEIGHT, annotationBlock.getYPosition());
        if (styleAnnotation != null) {
            xyAnnotation.setFont(new Font(styleAnnotation.getFontName(), Font.BOLD, styleAnnotation.getSize()));
            xyAnnotation.setPaint(styleAnnotation.getColor());
        } else {
            xyAnnotation.setFont(new Font("Nome", Font.BOLD, 8));
            xyAnnotation.setPaint(Color.BLACK);
        }

        xyAnnotation.setTextAnchor(TextAnchor.BOTTOM_LEFT);
        renderer.addAnnotation(xyAnnotation);
    }

    logger.debug("Annotation set");

    LookupPaintScale paintScale = new LookupPaintScale(0.5, ranges.size() + 0.5, color);
    String[] labels = new String[ranges.size() + 1];
    labels[0] = "";

    // ******************** SCALE ****************************
    for (Iterator iterator = ranges.iterator(); iterator.hasNext();) {
        RangeBlocks range = (RangeBlocks) iterator.next();
        Integer index = patternRangeIndex.get(range.getPattern());
        Color color = range.getColor();
        if (color != null) {
            //Paint colorTransparent=new Color(color.getRed(), color.getGreen(), color.getBlue(), 50);         
            Paint colorTransparent = null;
            if (addTransparency == true) {
                colorTransparent = new Color(color.getRed(), color.getGreen(), color.getBlue(), 50);
            } else {
                colorTransparent = new Color(color.getRed(), color.getGreen(), color.getBlue());
            }
            paintScale.add(index + 0.5, colorTransparent);
        }
        //String insertLabel="            "+range.getLabel();
        String insertLabel = range.getLabel();
        labels[index + 1] = insertLabel;
    }
    renderer.setPaintScale(paintScale);

    SymbolAxis scaleAxis = new SymbolAxis(null, labels);
    scaleAxis.setRange(0.5, ranges.size() + 0.5);
    scaleAxis.setPlot(new PiePlot());
    scaleAxis.setGridBandsVisible(false);

    org.jfree.chart.title.PaintScaleLegend psl = new PaintScaleLegend(paintScale, scaleAxis);
    psl.setMargin(new RectangleInsets(3, 10, 3, 10));
    psl.setPosition(RectangleEdge.BOTTOM);
    psl.setAxisOffset(5.0);
    // ******************** END SCALE ****************************

    logger.debug("Scale Painted");

    XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
    plot.setOrientation(PlotOrientation.HORIZONTAL);
    plot.setBackgroundPaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(5, 5, 5, 5));

    logger.debug("Plot set");

    JFreeChart chart = new JFreeChart(name, plot);
    if (styleTitle != null) {
        TextTitle title = setStyleTitle(name, styleTitle);
        chart.setTitle(title);
    }
    chart.removeLegend();
    chart.setBackgroundPaint(Color.white);
    chart.addSubtitle(psl);

    logger.debug("OUT");

    return chart;

}

From source file:com.rapidminer.gui.plotter.charts.DistributionPlotter.java

@Override
public void updatePlotter() {

    JFreeChart chart = null;/*  w w w  .j  a v a 2s.  c o m*/
    Attribute attr = null;
    if (plotColumn != -1 && createFromModel) {
        attr = model.getTrainingHeader().getAttributes().get(model.getAttributeNames()[plotColumn]);
    }
    if (attr != null && attr.isNominal()
            && attr.getMapping().getValues().size() > MAX_NUMBER_OF_DIFFERENT_NOMINAL_VALUES) {
        // showing no chart because of too many different values
        chart = new JFreeChart(new Plot() {

            private static final long serialVersionUID = 1L;

            @Override
            public String getPlotType() {
                return "empty";
            }

            @Override
            public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState,
                    PlotRenderingInfo info) {
                String msg = I18N.getGUILabel("plotter_panel.too_many_nominals", "Distribution Plotter",
                        DistributionPlotter.MAX_NUMBER_OF_DIFFERENT_NOMINAL_VALUES);
                g2.setColor(Color.BLACK);
                g2.setFont(g2.getFont().deriveFont(g2.getFont().getSize() * 1.35f));
                g2.drawChars(msg.toCharArray(), 0, msg.length(), 50, (int) (area.getHeight() / 2 + 0.5d));
            }
        });
        AbstractChartPanel panel = getPlotterPanel();
        // Chart Panel Settings
        if (panel == null) {
            panel = createPanel(chart);
        } else {
            panel.setChart(chart);
        }
        // ATTENTION: WITHOUT THIS WE GET SEVERE MEMORY LEAKS!!!
        panel.getChartRenderingInfo().setEntityCollection(null);
    } else {
        preparePlots();

        if (!createFromModel && (groupColumn < 0 || plotColumn < 0)) {
            CategoryDataset dataset = new DefaultCategoryDataset();
            chart = ChartFactory.createBarChart(null, // chart title
                    "Not defined", // x axis label
                    RANGE_AXIS_NAME, // y axis label
                    dataset, // data
                    PlotOrientation.VERTICAL, true, // include legend
                    true, // tooltips
                    false // urls
            );
        } else {
            try {
                if (model.isDiscrete(translateToModelColumn(plotColumn))) {
                    chart = createNominalChart();
                } else {
                    chart = createNumericalChart();
                }
            } catch (Exception e) {
                // do nothing - just do not draw the chart
            }
        }

        if (chart != null) {
            chart.setBackgroundPaint(Color.white);

            // get a reference to the plot for further customization...
            Plot commonPlot = chart.getPlot();
            commonPlot.setBackgroundPaint(Color.WHITE);
            if (commonPlot instanceof XYPlot) {
                XYPlot plot = (XYPlot) commonPlot;

                plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
                plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

                // domain axis
                if (dataTable != null) {
                    if (dataTable.isDate(plotColumn) || dataTable.isDateTime(plotColumn)) {
                        DateAxis domainAxis = new DateAxis(dataTable.getColumnName(plotColumn));
                        domainAxis.setTimeZone(com.rapidminer.tools.Tools.getPreferredTimeZone());
                        plot.setDomainAxis(domainAxis);
                    } else {
                        NumberAxis numberAxis = new NumberAxis(dataTable.getColumnName(plotColumn));
                        plot.setDomainAxis(numberAxis);
                    }
                }

                plot.getDomainAxis().setLabelFont(LABEL_FONT_BOLD);
                plot.getDomainAxis().setTickLabelFont(LABEL_FONT);

                plot.getRangeAxis().setLabelFont(LABEL_FONT_BOLD);
                plot.getRangeAxis().setTickLabelFont(LABEL_FONT);

                // ranging
                if (dataTable != null) {
                    Range range = getRangeForDimension(plotColumn);
                    if (range != null) {
                        plot.getDomainAxis().setRange(range, true, false);
                    }

                    range = getRangeForName(RANGE_AXIS_NAME);
                    if (range != null) {
                        plot.getRangeAxis().setRange(range, true, false);
                    }
                }

                // rotate labels
                if (isLabelRotating()) {
                    plot.getDomainAxis().setTickLabelsVisible(true);
                    plot.getDomainAxis().setVerticalTickLabels(true);
                }

            } else if (commonPlot instanceof CategoryPlot) {
                CategoryPlot plot = (CategoryPlot) commonPlot;

                plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
                plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

                plot.getRangeAxis().setLabelFont(LABEL_FONT_BOLD);
                plot.getRangeAxis().setTickLabelFont(LABEL_FONT);

                plot.getDomainAxis().setLabelFont(LABEL_FONT_BOLD);
                plot.getDomainAxis().setTickLabelFont(LABEL_FONT);
            }

            // legend settings
            LegendTitle legend = chart.getLegend();
            if (legend != null) {
                legend.setPosition(RectangleEdge.TOP);
                legend.setFrame(BlockBorder.NONE);
                legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
                legend.setItemFont(LABEL_FONT);
            }

            AbstractChartPanel panel = getPlotterPanel();
            // Chart Panel Settings
            if (panel == null) {
                panel = createPanel(chart);
            } else {
                panel.setChart(chart);
            }

            // ATTENTION: WITHOUT THIS WE GET SEVERE MEMORY LEAKS!!!
            panel.getChartRenderingInfo().setEntityCollection(null);
        }
    }
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphEngine.java

/**
 * Generates a simple Time Axis.//from w  w  w.  j a  v  a  2 s  . c  o m
 *
 * @return the generated Time Axis.
 */
private DateAxis generateTimeAxis() {
    DateAxis xAxis = new DateAxis("");
    xAxis.setLowerMargin(0.05);
    xAxis.setUpperMargin(0.02);
    xAxis.setLabel(null);
    xAxis.setTickLabelsVisible(true);
    xAxis.setTickMarksVisible(true);

    xAxis.setAxisLineVisible(true);
    xAxis.setNegativeArrowVisible(false);
    xAxis.setPositiveArrowVisible(false);
    xAxis.setVisible(true);
    xAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
    Locale locale = JiveGlobals.getLocale();
    // If the tick units have not yet been setup or the locale has changed
    if (tickUnits == null || !locale.equals(oldLocale)) {
        tickUnits = createTickUnits(locale, JiveGlobals.getTimeZone());
        oldLocale = locale;
    }
    xAxis.setStandardTickUnits(tickUnits);

    return xAxis;
}

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

/**
 * Method createChart./* www  . j a va 2s.  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:net.commerce.zocalo.freechart.ChartGenerator.java

public static JFreeChart createOverlaidOHLCAndStepChart(TimePeriodValuesCollection bottom,
        TimePeriodValuesCollection top, OHLCDataset ohlCdata) {
    DateAxis xAxis = new DateAxis(null);
    NumberAxis yAxis = new NumberAxis("price");
    yAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
    yAxis.setUpperBound(100);/*  w  w  w.  j  av  a 2 s.c o  m*/
    yAxis.setLowerBound(0.0);

    XYPlot plot = new XYPlot(null, xAxis, yAxis, null);
    plot.setDataset(0, bottom);
    plot.setDataset(1, top);
    plot.setDataset(2, ohlCdata);

    XYStepAreaRenderer bottomRenderer = new XYStepAreaRenderer(XYStepAreaRenderer.AREA, null, null);
    XYStepAreaRenderer topRenderer = new XYStepAreaRenderer(XYStepAreaRenderer.AREA, null, null);
    HighLowRenderer hiLoRenderer = new HighLowRenderer();

    topRenderer.setRangeBase(1.0);
    topRenderer.setSeriesPaint(0, new Color(204, 255, 153));
    bottomRenderer.setSeriesPaint(0, new Color(51, 255, 204));
    plot.setRenderer(bottomRenderer);
    plot.setRenderer(1, topRenderer);
    plot.setRenderer(2, hiLoRenderer);

    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setDomainCrosshairVisible(false);
    plot.setRangeCrosshairVisible(false);
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

    return new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
}

From source file:weka.classifiers.timeseries.eval.graph.JFreeChartDriver.java

protected JFreeChart getPredictedStepsChart(TSForecaster forecaster, List<ErrorModule> preds, String targetName,
        List<Integer> stepsToPlot, int instanceNumOffset, Instances data) {

    if (forecaster instanceof TSLagUser && data != null) {
        TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
        if (lagMaker.getAdjustForTrends() && !lagMaker.isUsingAnArtificialTimeIndex()) {

            // fill in any missing time stamps only
            data = new Instances(data);
            data = weka.classifiers.timeseries.core.Utils.replaceMissing(data, null,
                    lagMaker.getTimeStampField(), true, lagMaker.getPeriodicity(), lagMaker.getSkipEntries());
        }/*  www . j  a  v a 2  s  .co  m*/
    }

    // set up a collection of predicted series
    XYIntervalSeriesCollection xyDataset = new XYIntervalSeriesCollection();

    XYIntervalSeries targetSeries = new XYIntervalSeries(targetName, false, false);
    xyDataset.addSeries(targetSeries);
    // for (int i = 0; i < preds.size(); i++) {
    for (int z = 0; z < stepsToPlot.size(); z++) {
        int i = stepsToPlot.get(z);
        i--;
        // ignore out of range steps
        if (i < 0 || i >= preds.size()) {
            continue;
        }

        String step = "-steps";
        if (i == 0) {
            step = "-step";
        }
        targetSeries = new XYIntervalSeries(targetName + "_" + (i + 1) + step + "-ahead", false, false);
        xyDataset.addSeries(targetSeries);
    }

    ValueAxis timeAxis = null;
    NumberAxis valueAxis = new NumberAxis("");
    valueAxis.setAutoRangeIncludesZero(false);
    int timeIndex = -1;
    boolean timeAxisIsDate = false;
    if (forecaster instanceof TSLagUser && data != null) {
        TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
        if (!lagMaker.isUsingAnArtificialTimeIndex() && lagMaker.getAdjustForTrends()) {
            String timeName = lagMaker.getTimeStampField();
            if (data.attribute(timeName).isDate()) {
                timeAxis = new DateAxis("");
                timeAxisIsDate = true;
                timeIndex = data.attribute(timeName).index();
            }
        }
    }

    if (timeAxis == null) {
        timeAxis = new NumberAxis("");
        ((NumberAxis) timeAxis).setAutoRangeIncludesZero(false);
    }

    // now populate the series
    // for (int i = 0; i < preds.size(); i++) {
    boolean doneActual = false;
    boolean hasConfidenceIntervals = false;
    for (int z = 0; z < stepsToPlot.size(); z++) {
        int i = stepsToPlot.get(z);
        i--;

        // ignore out of range steps
        if (i < 0 || i >= preds.size()) {
            continue;
        }
        ErrorModule predsForStepI = preds.get(i);
        List<NumericPrediction> predsForTargetAtI = predsForStepI.getPredictionsForTarget(targetName);

        String step = "-steps";
        if (i == 0) {
            step = "-step";
        }
        int predIndex = xyDataset.indexOf(targetName + "_" + (i + 1) + step + "-ahead");
        XYIntervalSeries predSeries = xyDataset.getSeries(predIndex);
        XYIntervalSeries actualSeries = null;
        if (!doneActual) {
            int actualIndex = xyDataset.indexOf(targetName);
            actualSeries = xyDataset.getSeries(actualIndex);
        }

        for (int j = 0; j < predsForTargetAtI.size(); j++) {
            double x = Utils.missingValue();
            if (timeAxisIsDate) {
                if (instanceNumOffset + j + i < data.numInstances()) {
                    x = data.instance(instanceNumOffset + j + i).value(timeIndex);
                }
            } else {
                x = instanceNumOffset + j + i;
            }

            double yPredicted = predsForTargetAtI.get(j).predicted();
            double yHigh = yPredicted;
            double yLow = yPredicted;
            double[][] conf = predsForTargetAtI.get(j).predictionIntervals();
            if (conf.length > 0) {
                yLow = conf[0][0];
                yHigh = conf[0][1];
                hasConfidenceIntervals = true;
            }
            if (!Utils.isMissingValue(x) && !Utils.isMissingValue(yPredicted)) {
                if (predSeries != null) {
                    predSeries.add(x, x, x, yPredicted, yLow, yHigh);
                }
                // System.err.println("* " + yPredicted + " " + x);
            }

            if (!doneActual && actualSeries != null) {
                double yActual = predsForTargetAtI.get(j).actual();
                if (!Utils.isMissingValue(x) && !Utils.isMissingValue(yActual)) {
                    actualSeries.add(x, x, x, yActual, yActual, yActual);
                }
            }
        }

        if (actualSeries != null) {
            doneActual = true;
        }
    }

    // set up the chart
    String title = "";
    for (int i : stepsToPlot) {
        title += i + ",";
    }
    title = title.substring(0, title.lastIndexOf(","));
    title += " step-ahead predictions for " + targetName;

    /*
     * String algoSpec = forecaster.getAlgorithmName(); title += " (" + algoSpec
     * + ")";
     */

    if (forecaster instanceof WekaForecaster && hasConfidenceIntervals) {
        double confPerc = ((WekaForecaster) forecaster).getConfidenceLevel() * 100.0;
        title += " [" + Utils.doubleToString(confPerc, 0) + "% conf. intervals]";
    }

    XYErrorRenderer renderer = new XYErrorRenderer();
    renderer.setBaseLinesVisible(true);
    // renderer.setShapesFilled(true);
    XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, renderer);
    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    chart.setBackgroundPaint(java.awt.Color.white);
    TextTitle chartTitle = chart.getTitle();
    String fontName = chartTitle.getFont().getFontName();
    java.awt.Font newFont = new java.awt.Font(fontName, java.awt.Font.PLAIN, 12);
    chartTitle.setFont(newFont);

    return chart;
}

From source file:org.ash.history.detail.StackedChartDetail.java

/**
 * Creates the chart./*from  www . j av  a  2  s. com*/
 * 
 * @return the jfreechart
 */
private JFreeChart createChart() {

    xAxis = new DateAxis("time");
    xAxis.setLabel(null);

    chart = ChartFactory.createStackedXYAreaChart("", // chart title
            "X Value", // domain axis label
            "Active Sessions", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // the plot orientation
            xAxis, // xAxis
            false, // legend
            true, // tooltips
            false // urls
    );

    chart.getTitle()
            .setFont(new Font(TextTitle.DEFAULT_FONT.getFontName(), TextTitle.DEFAULT_FONT.getStyle(), 14));

    plot = (XYPlot) chart.getPlot();
    renderer = new StackedXYAreaRenderer3();
    renderer.setRoundXCoordinates(true);
    renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{0} ({1}, {2})",
            new SimpleDateFormat("HH:mm"), new DecimalFormat("0.0")));
    plot.setRenderer(0, renderer);
    plot.getRangeAxis().setLowerBound(0.0);
    plot.getRangeAxis().setAutoRange(true);

    // Set format for x axis
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("HH:mm"));

    // Add legend to right
    LegendTitle legend = new LegendTitle(chart.getPlot());

    BlockContainer wrapper = new BlockContainer(new BorderArrangement());
    wrapper.setFrame(new BlockBorder(1.0, 1.0, 1.0, 1.0));

    BlockContainer itemss = legend.getItemContainer();
    itemss.setPadding(2, 10, 5, 2);
    wrapper.add(itemss);
    legend.setWrapper(wrapper);

    legend.setPosition(RectangleEdge.RIGHT);
    legend.setHorizontalAlignment(HorizontalAlignment.LEFT);

    legend.setItemFont(new Font(LegendTitle.DEFAULT_ITEM_FONT.getFontName(),
            LegendTitle.DEFAULT_ITEM_FONT.getStyle(), 10));

    chart.addSubtitle(legend);

    return chart;
}