How to display bar value for each bar in a bar graph?

后端 未结 1 694
-上瘾入骨i
-上瘾入骨i 2021-01-03 08:20

There is a need to see the exact value that a bar in a bar graph represents, as opposed to the approximate value in the Y axis.

How can that be possibly done?

<
相关标签:
1条回答
  • 2021-01-03 08:42

    In iReport 3.7.6 you can just check "Show Labels" box under BarPlot properties.

    In a prior version (3.1.4), I had to create a ChartCustomizer class.

    If you need to format the number in the label (e.g. to Percentage, add thousands separator, etc), then you definitely need a ChartCustomizer, even in the new version.

    A simple example:

    import java.text.NumberFormat;
    
    import net.sf.jasperreports.engine.JRChart;
    import net.sf.jasperreports.engine.JRChartCustomizer;
    
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.labels.AbstractCategoryItemLabelGenerator;
    import org.jfree.chart.labels.CategoryItemLabelGenerator;
    import org.jfree.chart.plot.CategoryPlot;
    import org.jfree.chart.renderer.category.BarRenderer;
    import org.jfree.chart.renderer.category.CategoryItemRenderer;
    import org.jfree.data.category.CategoryDataset;
    
    
    public class SimpleBarChartCustomizer implements JRChartCustomizer {
    
        public void customize(JFreeChart chart, JRChart jasperChart) {
            CategoryPlot plot = chart.getCategoryPlot();
            BarRenderer renderer = (BarRenderer) plot.getRenderer();
    
            CategoryItemRenderer catRenderer = ((CategoryItemRenderer)renderer);
            catRenderer.setBaseItemLabelGenerator(new NumberLabelGenerator("", NumberFormat.getInstance()));
    
        }
    
        static class NumberLabelGenerator extends AbstractCategoryItemLabelGenerator implements CategoryItemLabelGenerator {
            public NumberLabelGenerator(String labelFormat,
                    NumberFormat formatter, NumberFormat percentFormatter) {
                super(labelFormat, formatter, percentFormatter);
            }
    
            protected NumberLabelGenerator(String labelFormat,  NumberFormat formatter) {
                super(labelFormat, formatter);
            }
    
            private NumberFormat formatter = NumberFormat.getInstance();
    
            public String generateLabel(CategoryDataset dataset, int series, int category) {
                Number b = dataset.getValue(series, category);
                formatter.setMaximumFractionDigits(2);
                return formatter.format(b);
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题