JFreeChart日期轴格式问题 [英] JFreeChart Date axis Formatting issue

查看:129
本文介绍了JFreeChart日期轴格式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时序图.我有x轴作为日期,而Y轴只是数字.我正在尝试在X轴上设置日期格式,但是我不断遇到异常.我的代码如下:

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?
                );

然后我尝试将x轴转换为简单的日期格式,如下所示:

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无法转换为org.jfree.chart.axis.DateAxis

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?

推荐答案

根据 向JFreeChart图添加日期/时间 :

……您正在使用ChartFactory.createXYLineChart(),这将为域创建NumberAxis.相反,请使用ChartFactory.createTimeSeriesChart(),这将为域创建DateAxis."-trashgod

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

这篇关于JFreeChart日期轴格式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆