JFreeChart Date axis Formatting issue
Asked Answered
A

2

5

I have a time series chart. I have my x-axis as a Date, and the Y-axis are just numbers. I am trying to format the date on the x-axis, however I keep getting exceptions. My code is below:

        TimeSeries trueSeries = new TimeSeries("True Data");
        TimeSeries regressionSeries = new TimeSeries("Regression Line");
        TimeSeries averageSeries = new TimeSeries("Moving Average");

        for (Date date : regression.keySet()) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int month = cal.get(Calendar.MONTH) + 1;
            int day = cal.get(Calendar.DAY_OF_MONTH);
            int year = cal.get(Calendar.YEAR);
            regressionSeries.add(new Day(day, month, year),
                    regression.get(date));
            averageSeries.add(new Day(day, month, year),
                    movingAverage.get(date));
            trueSeries.add(new Day(day, month, year), trueData.get(date));
        }
        TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(trueSeries);
        dataset.addSeries(regressionSeries);
        dataset.addSeries(averageSeries);
        JFreeChart chart = ChartFactory.createXYLineChart(
                stock.getCompanyName() + " (" + stock.getTicker() + ")",
                "Date", // x-axis Label
                "Close Price", // y-axis Label
                dataset, // Dataset
                PlotOrientation.VERTICAL, // Plot Orientation
                true, // Show Legend
                true, // Use tooltips
                false // Configure chart to generate URLs?
                );

And then I try to cast the x-axis into a simple date format, as follows:

XYPlot plot = (XYPlot) chart.getPlot();
DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy")); 

When I run this I get the following exception:

java.lang.ClassCastException: org.jfree.chart.axis.NumberAxis cannot be cast to org.jfree.chart.axis.DateAxis

Can somebody please tell me what I am doing wrong?

Arista answered 1/2, 2014 at 20:43 Comment(1)
Possible duplicate of Adding date/time to JFreeChart graphObrian
F
11

According to Adding date/time to JFreeChart graph:

"…you're using ChartFactory.createXYLineChart(), which creates a NumberAxis for the domain. Instead, use ChartFactory.createTimeSeriesChart(), which creates a DateAxis for the domain."—trashgod

Fetiparous answered 1/2, 2014 at 21:37 Comment(0)
D
3

Use

XYPlot plot = (XYPlot) chart.getPlot();
DateAxis dateAxis = new DateAxis();
dateAxis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy")); 
plot.setDomainAxis(dateAxis);

XYPlot.setDomainAxis accepts ValueAxis which is parent of DateAxis. So doing this will avoid the error.

Distinction answered 11/5, 2016 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.