1
votes

I need to be able to take a point, as returned from a MouseListener, and identify the nearest point in a scatter plot. I'm using JFreeChart with an XYDataset.

I have added a mouse listener to my ChartPanel, and am trying to compare these x,y values to those returned when I iterate through the data and check their locations. My code looks something like this:

ValueAxis domainAxis = chartPanel.getXYPlot().getDomainAxis();
ChartArea chartArea = chartPanel.getChartRenderingInfo().getChartArea();

for(int i=0; i < myXYData.getItemCount(0); i++) {
    double mouseX = e.getX(); // e is the MouseEvent
    double pointX = domainAxis.valueToJava2D(myXYData.getX(0, i), chartArea, RectangleEdge.BOTTOM);
    System.out.println("difference is " + (pointX - mouseX));
}

The problem is that the MouseEvent is reporting points relative to the top-left of the ChartPanel, so (0,0) is above the title, and left of the x-axis labels. The valueToJava2D method, however, is giving values relative to the area where the values are plotted, so (0,0) is below the graph title and to the right of the x-axis labels. This means that I get a non-zero difference when the mouse is directly over one of my data points!

How can I resolve this disparity?

thanks, Eric

1
Cross-posted here.trashgod

1 Answers

1
votes

I'd look at a ChartMouseListener, illustrated here and here.

If that is not sufficient, you may have to have to look at the axis, where the area and edge have meaning.

It may help to explain the goal, rather than your current approach. Alternatively, edit your question to include an sscce that shows your current approach. Many short examples may be found here.

Addendum: The practical limit on the max # of points is quite small.

For a reasonable number of points, you can enlarge the Shape, as shown here and here; see also ShapeUtilities. To call out details, consider a custom tooltip generator, examined here.