33Cursor Demo
44===========
55
6- This example shows how to use matplotlib to provide a data cursor. It
7- uses matplotlib to draw the cursor and may be a slow since this
8- requires redrawing the figure with every mouse move.
6+ This example shows how to use Matplotlib to provide a data cursor. It uses
7+ Matplotlib to draw the cursor and may be a slow since this requires redrawing
8+ the figure with every mouse move.
99
1010Faster cursoring is possible using native GUI drawing, as in
11- wxcursor_demo.py .
11+ :doc:`/gallery/user_interfaces/wxcursor_demo_sgskip` .
1212
13- The mpldatacursor and mplcursors third-party packages can be used to achieve a
14- similar effect. See
13+ The mpldatacursor__ and mplcursors__ third-party packages can be used to
14+ achieve a similar effect.
1515
16- https://github.com/joferkington/mpldatacursor
17- https://github.com/anntzer/mplcursors
16+ __ https://github.com/joferkington/mpldatacursor
17+ __ https://github.com/anntzer/mplcursors
1818"""
19+
1920import matplotlib .pyplot as plt
2021import numpy as np
2122
@@ -39,13 +40,13 @@ def mouse_move(self, event):
3940 self .ly .set_xdata (x )
4041
4142 self .txt .set_text ('x=%1.2f, y=%1.2f' % (x , y ))
42- plt .draw ()
43+ self . ax . figure . canvas .draw ()
4344
4445
4546class SnaptoCursor (object ):
4647 """
47- Like Cursor but the crosshair snaps to the nearest x,y point
48- For simplicity, I'm assuming x is sorted
48+ Like Cursor but the crosshair snaps to the nearest x, y point.
49+ For simplicity, this assumes that *x* is sorted.
4950 """
5051
5152 def __init__ (self , ax , x , y ):
@@ -58,13 +59,11 @@ def __init__(self, ax, x, y):
5859 self .txt = ax .text (0.7 , 0.9 , '' , transform = ax .transAxes )
5960
6061 def mouse_move (self , event ):
61-
6262 if not event .inaxes :
6363 return
6464
6565 x , y = event .xdata , event .ydata
66-
67- indx = min (np .searchsorted (self .x , [x ])[0 ], len (self .x ) - 1 )
66+ indx = min (np .searchsorted (self .x , x ), len (self .x ) - 1 )
6867 x = self .x [indx ]
6968 y = self .y [indx ]
7069 # update the line positions
@@ -73,16 +72,20 @@ def mouse_move(self, event):
7372
7473 self .txt .set_text ('x=%1.2f, y=%1.2f' % (x , y ))
7574 print ('x=%1.2f, y=%1.2f' % (x , y ))
76- plt .draw ()
75+ self .ax .figure .canvas .draw ()
76+
7777
7878t = np .arange (0.0 , 1.0 , 0.01 )
7979s = np .sin (2 * 2 * np .pi * t )
80- fig , ax = plt .subplots ()
8180
82- # cursor = Cursor(ax)
83- cursor = SnaptoCursor (ax , t , s )
84- plt .connect ('motion_notify_event' , cursor .mouse_move )
81+ fig , ax = plt .subplots ()
82+ ax .plot (t , s , 'o' )
83+ cursor = Cursor (ax )
84+ fig .canvas .mpl_connect ('motion_notify_event' , cursor .mouse_move )
8585
86+ fig , ax = plt .subplots ()
8687ax .plot (t , s , 'o' )
87- plt .axis ([0 , 1 , - 1 , 1 ])
88+ snap_cursor = SnaptoCursor (ax , t , s )
89+ fig .canvas .mpl_connect ('motion_notify_event' , snap_cursor .mouse_move )
90+
8891plt .show ()
0 commit comments