Search code examples
jfreechart

Jfree charts Labels overlapping


I am using Area Chart to draw the temperatures from database but as the data grows chart labels start getting merge. Please help me to get it fixed.


Solution

  • JFreeChart doesn't do any overlap detection for Area Chart. You have to implement your own Customizer and you can design an algo to skip some lables by just making them transparent.

    You have to create the class and implement

    net.sf.jasperreports.engine.JRChartCustomizer
    

    and write the logic in overridden method called customize. For example if you want to print label after 8th iteration then do as the done in the below code for reference.

    @Override
    public void customize(org.jfree.chart.JFreeChart chart, net.sf.jasperreports.engine.JRChart jasperChart) {
        org.jfree.chart.renderer.category.AreaRenderer renderer;
        org.jfree.chart.plot.CategoryPlot plot;
        org.jfree.chart.axis.NumberAxis rangeAxis;
        org.jfree.chart.axis.CategoryAxis axis;
        renderer = (org.jfree.chart.renderer.category.AreaRenderer) chart.getCategoryPlot().getRenderer();
    
        plot = chart.getCategoryPlot();
        rangeAxis = (org.jfree.chart.axis.NumberAxis) plot.getRangeAxis();
    
        axis = plot.getDomainAxis();
    
        CategoryAxis domainAxis = plot.getDomainAxis();
        CategoryLabelPositions pos = domainAxis.getCategoryLabelPositions();
         for (int i = 1; i <= plot.getCategories().size(); i++) {
                        if(i%8==0){
                        continue;
                        } else{
                            String cat_Name = (String) plot.getCategories().get(i-1);
                         domainAxis.setTickLabelPaint(cat_Names, new Color(0,0,0,0));
                           }
               }
           } 
    

    enter image description here