在jfreechart TimeSeriesCollection中如何显示只有值的日期?

时间:2012-09-06 10:17:15

标签: java jfreechart

public class Example {
    public static void main(String args[]){
        /*creating timeSeriesCollection*/
        TimeSeriesCollection dataset = new TimeSeriesCollection();
        TimeSeries timeSeries1 = new TimeSeries("Sample 1");
        timeSeries1.add(new Day(8,4, 2012), 7.0);
        timeSeries1.add(new Day(19,4, 2012), 5.0);
        dataset.addSeries(timeSeries1);
        /*Creating the chart*/
        JFreeChart chart = ChartFactory.createTimeSeriesChart("Population","Date","Population",dataset,true,true,false);
        /*Altering the graph */
        XYPlot plot = (XYPlot) chart.getPlot(); 
    plot.setAxisOffset(new RectangleInsets(5.0, 10.0, 10.0, 5.0));  
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer)plot.getRenderer();
    renderer.setBaseShapesVisible(true);
    renderer.setBaseShapesFilled(true);
    NumberAxis numberAxis = (NumberAxis)plot.getRangeAxis();        
    numberAxis.setRange(new Range(0,10));   
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy"));
    axis.setAutoTickUnitSelection(false);
    axis.setVerticalTickLabels(true);
        /* Displaying the chart*/           
        ChartFrame frame = new ChartFrame("Test", chart);
        frame.pack();
        frame.setVisible(true);
    }   
}

我编写了上面的代码,它完全正常,但在渲染图形时,它显示的是没有值的日期。它在y轴上显示9/4/1210/4/201218/4/2012等日期,但没有值。如何删除没有值的日期。为什么表现如此?

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:3)

试试这个:

  public class Example1 {
    public static void main(String args[]){

        DefaultKeyedValues data = new DefaultKeyedValues();
        data.addValue("8/4/2012" ,7.0);
        data.addValue("19/04/2012",5.0);

        CategoryDataset dataset = DatasetUtilities.createCategoryDataset("Population", data);
        JFreeChart chart = ChartFactory.createBarChart("Population","Date","Population",dataset,PlotOrientation.VERTICAL,true,true,false);
        ChartFrame frame = new ChartFrame("Test", chart);

        //Switch from a Bar Rendered to a LineAndShapeRenderer so the chart looks like an XYChart
        LineAndShapeRenderer renderer = new LineAndShapeRenderer();
        renderer.setBaseLinesVisible(false); //TUrn of the lines
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.setRenderer(0, renderer);

        NumberAxis numberAxis = (NumberAxis)plot.getRangeAxis();        
        numberAxis.setRange(new Range(0,10));   

        frame.pack();
        frame.setVisible(true);
    }   
}

enter image description here

而不是使用TimeSeriesChart使用CategoryDataSet作为@Dirk sugested,然后切换到LineAndShapeRenderer

答案 1 :(得分:2)

TimeSeries连续显示,这意味着日期沿轴均匀分布,即使此日期没有实际值。如果您只想显示某些日期,则应使用某种CategoryDataSet