javajasper-reportsjfreechartdynamic-jasper

How can I add horizontal line to bar chart in Jasper Report?


I'm trying to designing a report with bar chart, in which I need to add a threshold. I have tried with multi-axis chart, in which the scale in different axis is always different.

Is there any other solution to add line to bar chart?

My expect output is a chart as below: enter image description here


Solution

  • To draw a line on the bar chart you add a ValueMarker to the CategoryPlot.

    In jasper report this is done my adding a JRChartCustomizer

    public class MyChartCustomizer implements JRChartCustomizer {
    
        @Override
        public void customize(JFreeChart jfchart, JRChart jrchart) {
            CategoryPlot plot = (CategoryPlot) jfchart.getPlot();
            //Set at what value you like the line, its color and size of stroke
            ValueMarker vm = new ValueMarker(13000,Color.BLUE, new BasicStroke(2.0F));
            //add marker to plot
            plot.addRangeMarker(vm);
        }
    }
    

    In jrxml make sure your class is in classpath and set the customizerClass attribute on the chart tag

    <barChart>
        <chart customizerClass="MyChartCustomizer">
       ....
        </chart>
       ...
    </barChart>
    

    If you are using you can add it directly in code

    chart.addCustomizer(new DRIChartCustomizer() {      
        private static final long serialVersionUID = 1L;
        @Override
        public void customize(JFreeChart chart, ReportParameters arg1) {
            CategoryPlot plot = (CategoryPlot) jfchart.getPlot();
            ValueMarker vm = new ValueMarker(13000,Color.BLUE, new BasicStroke(2.0F));
            plot.addRangeMarker(vm);
        }
    });
    

    If you are using setCustomizerClass (as in jrxml)

    DJBarChartBuilder().setCustomizerClass("MyChartCustomizer");
    

    Example of result

    Chart

    Note: in example no package name is used, if MyChartCustomizer is in a package full package name needs to be indicated in setCustomizerClass example "my.package.MyChartCustomizer"