Search code examples
jfreechart

Position label text on conditional basis


enter image description here

In the above bar chart, for the grey bar I want the label text (Threshold 50%) to be displayed inside the grey bar. Currently its showing outside because of the below code

renderer.setBaseItemLabelPaint(Color.red);
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
                    ItemLabelAnchor.OUTSIDE3, TextAnchor.CENTER_LEFT,
                    TextAnchor.CENTER, 0.0));

How to I apply the above condition only to the 2nd red bar & not to other bars

Here is my dataset

cat Category       Value
0                  0.000000
1   You 10%        0.100000
2   Threshold 50%  0.500000

Solution

  • This could be achieved by overriding getPositiveItemLabelPosition method of AbstractCategoryItemRenderer java class.

    @Override
        public ItemLabelPosition getPositiveItemLabelPosition(int row,
                int column) {
            CategoryDataset dataset = getPlot().getDataset();
            double value = dataset.getValue(row, column).doubleValue();
            if (value < 0.15) {
                return new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3,
                        TextAnchor.CENTER_LEFT, TextAnchor.CENTER, 0.0);
            } else {
                return new ItemLabelPosition(ItemLabelAnchor.INSIDE3,
                        TextAnchor.CENTER_RIGHT, TextAnchor.CENTER, 0.0);
            }
    
        }