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

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

Introduction

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

Prototype

@Override
public void setRange(double lower, double upper) 

Source Link

Document

Sets the axis range and sends an AxisChangeEvent to all registered listeners.

Usage

From source file:org.jfree.chart.demo.CompareToPreviousYearDemo.java

private static JFreeChart createChart() {
    XYDataset xydataset = createDataset2006();
    XYDataset xydataset1 = createDataset2007();
    DateAxis dateaxis = new DateAxis("Date");
    Month month = new Month(1, 2007);
    Month month1 = new Month(12, 2007);
    dateaxis.setRange(month.getFirstMillisecond(), month1.getLastMillisecond());
    dateaxis.setDateFormatOverride(new SimpleDateFormat("MMM"));
    dateaxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
    XYLineAndShapeRenderer xylineandshaperenderer = new XYLineAndShapeRenderer();
    xylineandshaperenderer.setUseFillPaint(true);
    xylineandshaperenderer.setBaseFillPaint(Color.white);
    xylineandshaperenderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{1}: {2}",
            new SimpleDateFormat("MMM-yyyy"), new DecimalFormat("0.00")));
    XYPlot xyplot = new XYPlot(xydataset1, dateaxis, new NumberAxis("Sales"), xylineandshaperenderer);
    xyplot.setDomainPannable(true);//from w  w  w  .ja  v a2  s  . co  m
    xyplot.setRangePannable(true);
    DateAxis dateaxis1 = new DateAxis();
    dateaxis1.setVisible(false);
    xyplot.setDomainAxis(1, dateaxis1);
    xyplot.setDataset(1, xydataset);
    xyplot.mapDatasetToDomainAxis(1, 1);
    XYLineAndShapeRenderer xylineandshaperenderer1 = new XYLineAndShapeRenderer();
    xylineandshaperenderer1.setSeriesPaint(0, Color.blue);
    xylineandshaperenderer1.setUseFillPaint(true);
    xylineandshaperenderer1.setBaseFillPaint(Color.white);
    xylineandshaperenderer1.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{1}: {2}",
            new SimpleDateFormat("MMM-yyyy"), new DecimalFormat("0.00")));
    xyplot.setRenderer(1, xylineandshaperenderer1);
    JFreeChart jfreechart = new JFreeChart("Sales Comparison Chart", xyplot);
    xyplot.setDomainCrosshairVisible(true);
    xyplot.setRangeCrosshairVisible(true);
    DateAxis dateaxis2 = (DateAxis) xyplot.getDomainAxis();
    dateaxis2.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));
    ChartUtilities.applyCurrentTheme(jfreechart);
    return jfreechart;
}

From source file:org.posterita.businesslogic.performanceanalysis.CustomPOSReportManager.java

public static TimeSeriesChart generateTimeSeriesChart(Properties ctx, String title, String subtitle,
        int account_id, Timestamp fromDate, Timestamp toDate, String salesGroup, String priceQtyFilter)
        throws OperationException {
    TimeSeriesChart timeSeriesChart = new TimeSeriesChart();
    timeSeriesChart.setTitle(title);//from w  ww.j  a  v  a  2 s.c  om
    timeSeriesChart.setSubtitle(subtitle);
    timeSeriesChart.setShowShapes(true);
    //timeSeriesChart.getDataSetFromSQL(timeSeriesChartSQL);

    String timeSeriesChartSQL = SalesAnalysisReportManager.getTimeSeriesDataSetSQL(ctx, account_id, fromDate,
            toDate, salesGroup);
    ArrayList<Object[]> list = ReportManager.getReportData(ctx, timeSeriesChartSQL, false);

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    TimeSeries series = null;
    String yLabel = null;

    String seriesName = null;
    String date = null;
    BigDecimal price = null;
    String[] s = null;
    int day, month, year;

    for (Object[] data : list) {
        seriesName = (String) data[0];
        date = (String) data[1];
        price = (BigDecimal) data[2];
        s = date.split("-");

        if (s.length != 3)
            throw new OperationException("Unable to generate timeseries. "
                    + "Cause:Invalid date format, the date returned should have the following format 'DD-MM-YYYY'");

        SimpleDateFormat sdf = new SimpleDateFormat();
        Calendar cal = Calendar.getInstance();
        Date d = null;

        try {
            sdf.applyPattern("dd-MM-yyyy");
            d = sdf.parse(date);
        } catch (ParseException e1) {
            try {
                sdf.applyPattern("dd-MMM-yyyy");
                d = sdf.parse(date);
            } catch (ParseException e) {
                throw new OperationException("Unable to generate timeseries. "
                        + "Cause:Invalid date format, the date returned should have one of the following formats 'DD-MM-YYYY' or 'DD-MMM-YYYY'",
                        e);
            }
        }

        cal.setTime(d);

        day = cal.get(Calendar.DATE);
        month = cal.get(Calendar.MONTH) + 1;
        year = cal.get(Calendar.YEAR);

        series = dataset.getSeries(seriesName);

        if (series == null) {
            series = new TimeSeries(seriesName, Day.class);
            series.add(new Day(day, month, year), price);

            dataset.addSeries(series);
        } else {
            series.add(new Day(day, month, year), price);
        } //if   

    } //for

    if (priceQtyFilter.equalsIgnoreCase(Constants.PRICE)) {
        //against price
        String currency = POSTerminalManager.getDefaultSalesCurrency(ctx).getCurSymbol();
        yLabel = "Value (" + currency + ")";
    } else {
        yLabel = "Quantity";
    }

    timeSeriesChart.setYLabel(yLabel);
    timeSeriesChart.setDataset(dataset);
    XYPlot plot = (XYPlot) timeSeriesChart.getChart().getPlot();
    DateAxis axis = (DateAxis) plot.getDomainAxis();

    SimpleDateFormat sdf = new SimpleDateFormat(TimestampConvertor.DEFAULT_DATE_PATTERN1);

    axis.setRange(fromDate, toDate);
    //axis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH,1,new SimpleDateFormat("MMM-yyyy")));        
    timeSeriesChart.getChart().setBackgroundPaint(Color.white);

    return timeSeriesChart;
}

From source file:jgnash.ui.commodity.SecuritiesHistoryDialog.java

private static JFreeChart createChart(final SecurityNode node) {
    Objects.requireNonNull(node);

    final List<SecurityHistoryNode> hNodes = node.getHistoryNodes();
    final Date max = DateUtils.asDate(hNodes.get(hNodes.size() - 1).getLocalDate());
    final Date min = DateUtils.asDate(hNodes.get(0).getLocalDate());

    final DateAxis timeAxis = new DateAxis(null);
    timeAxis.setVisible(false);// w  w w.jav  a2  s .c  om
    timeAxis.setAutoRange(false);
    timeAxis.setRange(min, max);

    final NumberAxis valueAxis = new NumberAxis(null);
    valueAxis.setAutoRangeIncludesZero(false);
    valueAxis.setVisible(false);

    final XYAreaRenderer renderer = new XYAreaRenderer();
    renderer.setBaseToolTipGenerator(new SecurityItemLabelGenerator(node));
    renderer.setOutline(true);
    renderer.setSeriesPaint(0, new Color(225, 247, 223));

    final XYPlot plot = new XYPlot(null, timeAxis, valueAxis, renderer);

    final List<List<SecurityHistoryNode>> groups = node.getHistoryNodeGroupsBySplits();

    for (int i = 0; i < groups.size(); i++) {
        int size = groups.get(i).size();

        Date[] date = new Date[size];
        double[] high = new double[size];
        double[] low = new double[size];
        double[] open = new double[size];
        double[] close = new double[size];
        double[] volume = new double[size];

        for (int j = 0; j < size; j++) {
            final SecurityHistoryNode hNode = groups.get(i).get(j);

            date[j] = DateUtils.asDate(hNode.getLocalDate());
            high[j] = hNode.getAdjustedHigh().doubleValue();
            low[j] = hNode.getAdjustedLow().doubleValue();
            open[j] = hNode.getAdjustedPrice().doubleValue();
            close[j] = hNode.getAdjustedPrice().doubleValue();
            volume[j] = hNode.getVolume();
        }

        final AbstractXYDataset data = new DefaultHighLowDataset(node.getDescription() + i, date, high, low,
                open, close, volume);
        plot.setDataset(i, data);
    }

    plot.setInsets(new RectangleInsets(1, 1, 1, 1));

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

    return chart;
}

From source file:no.met.jtimeseries.netcdf.plot.MultiPlotProvider.java

public XYPlot getPlot(List<NumberPhenomenon> dataList) {
    DateAxis domainAxis = new DateAxis("T", TimeZone.getTimeZone("UTC"), Locale.getDefault());
    domainAxis.setRange(dataList.get(0).getStartTime(), dataList.get(0).getEndTime());

    CombinedDomainXYPlot plot = new CombinedDomainXYPlot(domainAxis);

    for (PlotProvider provider : subProviders) {

        List<String> variables = dataForProviders.get(provider);
        if (variables == null)
            plot.add(provider.getPlot(dataList));
        else/*from  w w  w.  j ava 2 s  . c o m*/
            plot.add(provider.getPlot(extractNumberPhenomena(variables, dataList)));
    }

    return plot;
}

From source file:org.jfree.chart.demo.TimeSeriesDemo11.java

/**
 * A demonstration application showing how to...
 *
 * @param title  the frame title.//from   w  w  w. j  a  v  a2s  . c om
 */
public TimeSeriesDemo11(final String title) {

    super(title);
    final JPanel panel = new JPanel(new GridLayout(2, 2));
    panel.setPreferredSize(new java.awt.Dimension(800, 600));

    final Day today = new Day();
    final XYDataset dataset = createDataset("Series 1", 100.0, today, 365);

    final JFreeChart chart1 = createChart("Chart 1 : 1 Year", dataset);
    final ChartPanel chartPanel1 = new ChartPanel(chart1);
    panel.add(chartPanel1);

    final JFreeChart chart2 = createChart("Chart 2 : 6 Months", dataset);
    final SerialDate t = today.getSerialDate();
    final SerialDate t6m = SerialDate.addMonths(-6, t);
    final Day sixMonthsAgo = new Day(t6m);
    final DateAxis axis2 = (DateAxis) chart2.getXYPlot().getDomainAxis();
    axis2.setRange(sixMonthsAgo.getStart(), today.getEnd());
    final ChartPanel chartPanel2 = new ChartPanel(chart2);
    panel.add(chartPanel2);

    final JFreeChart chart3 = createChart("Chart 3 : 3 Months", dataset);
    final SerialDate t3m = SerialDate.addMonths(-3, t);
    final Day threeMonthsAgo = new Day(t3m);
    final DateAxis axis3 = (DateAxis) chart3.getXYPlot().getDomainAxis();
    axis3.setRange(threeMonthsAgo.getStart(), today.getEnd());
    final ChartPanel chartPanel3 = new ChartPanel(chart3);
    panel.add(chartPanel3);

    final JFreeChart chart4 = createChart("Chart 4 : 1 Month", dataset);
    final SerialDate t1m = SerialDate.addMonths(-1, t);
    final Day oneMonthsAgo = new Day(t1m);
    final DateAxis axis4 = (DateAxis) chart4.getXYPlot().getDomainAxis();
    axis4.setRange(oneMonthsAgo.getStart(), today.getEnd());
    final ChartPanel chartPanel4 = new ChartPanel(chart4);
    panel.add(chartPanel4);

    setContentPane(panel);

}

From source file:no.met.jtimeseries.netcdf.plot.SimplePlotProvider.java

/**
 * Create a domain axis for the data.//  ww  w.  jav a 2s .c  om
 * 
 * @param dataList List to create axis from
 * @return An axis for plotting, with time elements
 */
private DateAxis getDomainAxis(List<NumberPhenomenon> dataList) {
    DateAxis domainAxis = new DateAxis();
    domainAxis.setRange(dataList.get(0).getStartTime(), dataList.get(0).getEndTime());
    return domainAxis;
}

From source file:org.tolven.analysis.bean.PercentTimeSeriesBean.java

private JFreeChart getChart(String dataSeriesTitle, String targetSeriesTitle, List<MenuData> snapshots,
        Date fromDate, Date toDate, Class<?> intervalUnitClass) {
    TimeSeries dataTimeSeries = new TimeSeries(dataSeriesTitle);
    TimeSeries targetTimeSeries = null;//from w ww.  j av  a2 s  .c o  m
    if (targetSeriesTitle != null) {
        targetTimeSeries = new TimeSeries(targetSeriesTitle);
    }
    for (MenuData snapshot : snapshots) {
        Date snapshotDate = snapshot.getDate01();
        long nSnapshotresultsNumerator = snapshot.getLongField("normCount");
        long nSnapshotresultsDenominator = snapshot.getLongField("allCount");
        Double value = null;
        if (nSnapshotresultsDenominator == 0) {
            value = 0d;
        } else {
            value = 1d * nSnapshotresultsNumerator / nSnapshotresultsDenominator;
        }
        RegularTimePeriod regTimePeriod = RegularTimePeriod.createInstance(intervalUnitClass, snapshotDate,
                TimeZone.getDefault());
        dataTimeSeries.addOrUpdate(regTimePeriod, value);
        if (targetTimeSeries != null) {
            Double targetPercent = snapshot.getDoubleField("targetPercent") / 100;
            targetTimeSeries.addOrUpdate(regTimePeriod, targetPercent);
        }
    }
    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();
    timeSeriesCollection.addSeries(dataTimeSeries);
    if (targetTimeSeries != null) {
        timeSeriesCollection.addSeries(targetTimeSeries);
    }
    XYDataset xyDataset = (XYDataset) timeSeriesCollection;
    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, // title
            null, // x-axis label
            null, // y-axis label
            xyDataset, // data
            true, // create legend?
            false, // generate tooltips?
            false // generate URLs?
    );
    chart.setBackgroundPaint(Color.white);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.BLACK);
    plot.setDomainGridlinesVisible(false);
    XYItemRenderer r = plot.getRenderer();
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
    renderer.setBaseShapesVisible(true);
    renderer.setBaseShapesFilled(true);
    renderer.setSeriesShape(0, new Ellipse2D.Double(-3, -3, 6, 6));
    renderer.setSeriesPaint(0, Color.BLUE);
    renderer.setSeriesShape(1, new Rectangle2D.Double(-3, -3, 6, 6));
    renderer.setSeriesPaint(1, Color.RED);
    NumberAxis vaxis = (NumberAxis) plot.getRangeAxis();
    vaxis.setAutoRange(true);
    vaxis.setAxisLineVisible(true);
    vaxis.setNumberFormatOverride(NumberFormat.getPercentInstance());
    vaxis.setTickMarksVisible(true);
    DateAxis daxis = (DateAxis) plot.getDomainAxis();
    daxis.setRange(fromDate, toDate);
    if (intervalUnitClass == Month.class) {
        DateFormatSymbols dateFormatSymbols = new DateFormatSymbols();
        dateFormatSymbols
                .setShortMonths(new String[] { "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" });
        daxis.setDateFormatOverride(new SimpleDateFormat("MMM", dateFormatSymbols));
    }
    return chart;
}

From source file:org.n52.io.img.ChartRenderer.java

private void configureTimeAxis(XYPlot xyPlot) {
    String timespan = getChartStyleDefinitions().getTimespan();
    DateAxis timeAxis = (DateAxis) xyPlot.getDomainAxis();
    timeAxis.setRange(getStartTime(timespan), getEndTime(timespan));
    timeAxis.setDateFormatOverride(new SimpleDateFormat());
}

From source file:org.n52.io.measurement.img.ChartIoHandler.java

private void configureTimeAxis(XYPlot xyPlot) {
    DateAxis timeAxis = (DateAxis) xyPlot.getDomainAxis();
    timeAxis.setRange(getStartTime(getTimespan()), getEndTime(getTimespan()));

    String timeformat = "yyyy-MM-dd, HH:mm";
    if (getChartStyleDefinitions().containsParameter("timeformat")) {
        timeformat = getChartStyleDefinitions().getAsString("timeformat");
    }/*  w  w  w  .  ja  v  a 2  s .  co m*/
    DateFormat requestTimeFormat = new SimpleDateFormat(timeformat, i18n.getLocale());
    requestTimeFormat.setTimeZone(getTimezone().toTimeZone());
    timeAxis.setDateFormatOverride(requestTimeFormat);
    timeAxis.setTimeZone(getTimezone().toTimeZone());
}

From source file:org.posterita.struts.pos.POSSalesReportAction.java

public ActionForward getCustomReport(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws OperationException, ApplicationException {
    ActionForward fwd = init(mapping, form, request, response);
    if (fwd != null)
        return fwd;

    Properties ctx = TmkJSPEnv.getCtx(request);
    DefaultForm df = (DefaultForm) form;

    ReportBean bean = (ReportBean) df.getBean();
    Timestamp fromDate = ReportDateManager.getFromDate(bean);
    Timestamp toDate = ReportDateManager.getToDate(bean);
    String timeperiod = bean.getTimePeriod();
    String chartType = bean.getChartType();
    String salesGroup = bean.getSalesGroup();

    String reportDir = ReportManager.getReportDirectoryFromServletContext(this.servlet);
    String filename = RandomStringGenerator.randomstring();

    String subtitle = null;//from   www . j  a  va  2  s.  c  om
    String title = null;

    if (timeperiod != null) {
        subtitle = "For " + timeperiod;
    } else {
        subtitle = "For period:" + fromDate + " to " + toDate;
    }

    if (salesGroup.equalsIgnoreCase(Constants.REVENUE_RECOGNITION)
            || salesGroup.equalsIgnoreCase(Constants.ATTRIBUTESET)) {
        title = "Sales By " + salesGroup;
    } else {
        String[] s = salesGroup.split("_");

        if (s.length != 2) {
            throw new OperationException("Cannot generate sql. Unknown salesGroup parameter:" + salesGroup);
        }

        int attributeSetId = Integer.parseInt(s[0]);
        int attributeId = Integer.parseInt(s[1]);

        String attributeSetName = null;
        String attributeName = null;

        attributeSetName = MAttributeSet.get(ctx, attributeSetId).getName();
        attributeName = new MAttribute(ctx, attributeId, null).getName();

        title = "Sales By " + attributeName + " For " + attributeSetName;
    }

    if (chartType.equals(PieChart.CHART_TYPE)) {
        //draw pie chart
        String pieChartSQL = SalesAnalysisReportManager.getPieChartDataSetSQL(ctx, Integer.valueOf(1), fromDate,
                toDate, salesGroup);
        PieChart pieChart = new PieChart();

        pieChart.setTitle(title);
        pieChart.setSubtitle(subtitle);
        pieChart.getDataSetFromSQL(pieChartSQL);
        pieChart.getChart().setBackgroundPaint(Color.white);
        pieChart.saveChartAsJPEG(reportDir + filename + ".jpg", 700, 600);
    } else if (chartType.equals(TimeSeriesChart.CHART_TYPE)) {
        //draw timeseries
        String timeSeriesChartSQL = SalesAnalysisReportManager.getTimeSeriesDataSetSQL(ctx, Integer.valueOf(1),
                fromDate, toDate, salesGroup);
        TimeSeriesChart timeSeriesChart = new TimeSeriesChart();

        timeSeriesChart.setTitle(title);
        timeSeriesChart.setSubtitle(subtitle);
        timeSeriesChart.setShowShapes(true);
        timeSeriesChart.getDataSetFromSQL(timeSeriesChartSQL);

        XYPlot plot = (XYPlot) timeSeriesChart.getChart().getPlot();
        DateAxis axis = (DateAxis) plot.getDomainAxis();

        axis.setRange(fromDate, toDate);
        //axis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH,1,new SimpleDateFormat("MMM-yyyy")));

        timeSeriesChart.getChart().setBackgroundPaint(Color.white);
        timeSeriesChart.saveChartAsJPEG(reportDir + filename + ".jpg", 700, 600);
    } else {
        throw new OperationException("Invalid Chart type:" + chartType);
    }

    String imgURL = request.getContextPath() + "/config/reports/" + filename + ".jpg";
    request.getSession().setAttribute(Constants.REPORT_URL, imgURL);

    return mapping.findForward(GET_CUSTOM_REPORT);
    //return getGroupedSalesReport(mapping,form,request,response);
}