Search code examples
javajfreechart

XYPlot: Annotation is placed incorrectly with respect to Y axis


I have the following code that generates an annotation in the XYPlot on the on-mouse-click event.

    _chartPanel.addChartMouseListener(new ChartMouseListener() {
        @Override
        public void chartMouseClicked(ChartMouseEvent cme) 
        {
            Rectangle2D dataArea = _chartPanel.getScreenDataArea();
            XYPlot plot = (XYPlot) cme.getChart().getPlot();
            plot.clearAnnotations();
            ValueAxis xAxis = plot.getDomainAxis();
            ValueAxis yAxis = plot.getRangeAxis();
            double x = xAxis.java2DToValue(cme.getTrigger().getX(), dataArea, RectangleEdge.BOTTOM);
            double y = yAxis.java2DToValue(cme.getTrigger().getY(), dataArea, RectangleEdge.BOTTOM);
            if (!xAxis.getRange().contains(x)) { 
                x = Double.NaN;                  
            }                
            DecimalFormat df = new DecimalFormat("#.##");
            df.setRoundingMode(RoundingMode.CEILING);
            XYPointerAnnotation pt = new XYPointerAnnotation("Lat: " + df.format(y) + "\n Lon: " + df.format(x), x, y, 0.2);
            //pt.setBackgroundPaint(Color.red);
            pt.setArrowPaint(Color.red);
            pt.setFont(_font);
            pt.setPaint(Color.red);
            plot.addAnnotation(pt);
        }

Everything works fine except Y axis (see example below). When I click on the series point (red arrow), the annotation appears in another place (the location is correct with respect to X-axis, while it's incorrect with respect to Y).

enter image description here


Solution

  • When you call java2dToValue() to calculate the y-value, you are specifying RectangleEdge.BOTTOM for the axis location, but it should be RectangleEdge.LEFT.