我有时间序列图表。我的x轴是日期,Y轴只是数字。我试图在x轴上格式化日期,但是我一直在例外。我的代码如下:
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?
);
然后我尝试将x轴转换为简单的日期格式,如下所示:
XYPlot plot = (XYPlot) chart.getPlot();
DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy"));
当我运行时,我得到以下异常:
java.lang.ClassCastException:org.jfree.chart.axis.NumberAxis无法强制转换为org.jfree.chart.axis.DateAxis
有人可以告诉我我做错了吗?
答案 0 :(得分:7)
根据Adding date/time to JFreeChart graph:
“...您正在使用
ChartFactory.createXYLineChart()
,为域名创建NumberAxis
。而是使用ChartFactory.createTimeSeriesChart()
,为域名创建DateAxis
。” - trashgod
答案 1 :(得分:1)
使用
XYPlot plot = (XYPlot) chart.getPlot();
DateAxis dateAxis = new DateAxis();
dateAxis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy"));
plot.setDomainAxis(dateAxis);
XYPlot.setDomainAxis接受ValueAxis,它是DateAxis的父级。这样做可以避免错误。