4
votes

I have made it possible for value labels to appear on top of the bar in JFreeChart. However, it would look better if the labels are inside the bars. How do I make this work? The image below shows what I wanted the graph to look like.

Bar Graph with Label inside bar

4

4 Answers

9
votes

I used the following code to make it work:

StackedBarRenderer renderer = new StackedBarRenderer(false);
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
chart.getCategoryPlot().setRenderer(renderer);`
5
votes

You can use ItemLabelPosition DOC Here

renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,TextAnchor.TOP_CENTER  ))

Output :-

enter image description here

5
votes

Just specify the desired ItemLabelPosition in your CategoryItemLabelGenerator. BarChartDemo3 is an example, shown here.

0
votes

As fixing positions use ItemLabelPosition

CategoryPlot plot = chart.getCategoryPlot();
CategoryItemRenderer renderer = plot.getRenderer(); 
CategoryItemLabelGenerator generator = new StandardCategoryItemLabelGenerator("{2}", NumberFormat.getInstance()); 

renderer.setItemLabelGenerator(generator); 
renderer.setItemLabelFont(new Font("SansSerif", Font.PLAIN, 12)); //just font change optional 
renderer.setItemLabelsVisible(true); 
renderer.setPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, - 0 / 2)); 

It will show your value in the Center of your bar. You can modify the position as per your requirements.