Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFreeChart Date axis Formatting issue

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?

like image 610
Suraj Kulkarni Avatar asked Feb 01 '14 20:02

Suraj Kulkarni


2 Answers

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

like image 91
Paul Facklam Avatar answered Nov 06 '22 11:11

Paul Facklam


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.

like image 22
Chirag Agrawal Avatar answered Nov 06 '22 11:11

Chirag Agrawal