Search code examples
javadatejfreechart

JFreeChart issue with dates


Hello I am unable to display the dates in a JFreeChart. However the dates are included in the TimeSeries. Here's what I see in the debugger:

The dates are included

But the only thing I can see is the following: X axis does not show the dates

Here's my code:

public XYDataset createDataset() {
        TimeSeries series1 = new TimeSeries(PortfolioValueChart.CHART_NAME_PORTFOLIO);
        for (PriceAction pa : positionPrices.getPrices()) {
            series1.add(pa.date.toRegularTimePeriod(), pa.close);
        }

        TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(series1);
        return dataset;
    }

JFreeChart portfolioValueChart = PortfolioValueChart.getChart(financialPosition);
ChartPanel portfolioValuePanel = new ChartPanel(portfolioValueChart);

Solution

  • Remember to use a

    TimeSeriesChart
    

    such as:

    JFreeChart chart = ChartFactory.createTimeSeriesChart(...)
    

    With Javadoc:

    public static JFreeChart createTimeSeriesChart​(String title,
    String timeAxisLabel,
    String valueAxisLabel,
    XYDataset dataset,
    boolean legend,
    boolean tooltips,
    boolean urls)
    Creates and returns a time series chart. A time series chart is an XYPlot with a DateAxis for the x-axis and a NumberAxis for the y-axis. The default renderer is an XYLineAndShapeRenderer.
    A convenient dataset to use with this chart is a TimeSeriesCollection.
    
    Parameters:
    title - the chart title (null permitted).
    timeAxisLabel - a label for the time axis (null permitted).
    valueAxisLabel - a label for the value axis (null permitted).
    dataset - the dataset for the chart (null permitted).
    legend - a flag specifying whether or not a legend is required.
    tooltips - configure chart to generate tool tips?
    urls - configure chart to generate URLs?
    Returns:
    A time series chart.