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?
According to Adding date/time to JFreeChart graph:
"…you're using
ChartFactory.createXYLineChart()
, which creates aNumberAxis
for the domain. Instead, useChartFactory.createTimeSeriesChart()
, which creates aDateAxis
for the domain."—trashgod
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With