Search code examples
wolfram-mathematicawolframalpha

How do I get the crosshair behavior of Wolfram|Alpha 2D graphics in Mathematica?


When the mouse cursor is over a 2D plot in Wolfram|Alpha, a pair of grey lines appear that help you read the coordinates off the x and y axes. For example, I have the mouse over one of the turning points in the following plot of the Airy function.

Web

The above can also be obtained inside Mathematica using

WolframAlpha["Plot Ai(x)", {{"Plot", 1}, "Content"}]

Nb

which has the added advantage of some sort of locator showing the coordinates.


How can I emulate such behavior in a normal Mathematica graphics/plot?


Solution

  • Here's another approach using Nearest, that's a bit different from Simon's:

    plot = Plot[{Sin[x], Cos[x]}, {x, -2 Pi, 2 Pi}];
    With[{nf = Nearest[Flatten[Cases[Normal[plot], Line[p_, ___] :> p, Infinity], 1]]},
       Show[plot, 
          Epilog -> 
             Dynamic[DynamicModule[{
                pt = First[nf[MousePosition[{"Graphics", Graphics}, {0, 0}]]], 
                scaled = Clip[MousePosition[{"GraphicsScaled", Graphics}, {0, 0}], {0, 1}]
                }, 
               {
                {If[scaled === None, {}, 
                   {Lighter@Gray, Line[{
                       {Scaled[{scaled[[1]], 1}], Scaled[{scaled[[1]], 0}]}, 
                       {Scaled[{1, scaled[[2]]}], Scaled[{0, scaled[[2]]}]}
                       }]
                   }]}, 
                {AbsolutePointSize[7], Point[pt], White, AbsolutePointSize[5], Point[pt]},
                Text[Style[NumberForm[Row[pt, ", "], {5, 2}], 12, Background -> White], Offset[{7, 0}, pt], {-1, 0}]}
             ]]
        ]
     ]
    

    This was put together from example I had laying around. (I don't like the free-floating drop-lines combined with the point tracking; either on its own feels fine.)