0

I would like to add a cursor to Matplotlib as in this thread: Add cursor to matplotlib

I tried to change that code to use the data I have stored in a csv, but with no success. I am using pandas and "read_csv" to import the contents of the file and then convert the data frame/series to a list.

I would appreciates well, if you could tell me the meaning of the following line of code: indx = np.searchsorted(self.x, [x])[0]

Maybe I am wrong, but as the mouse moves, I think I only need to grab those coordinates and not using the "searchsorted" function but I really don't know.

Thanks in advance. Best regards, Pedro

Edit 14/09/2020

class SnaptoCursor(object):
    def __init__(self, ax, x, y):
        self.ax = ax
        self.ly = ax.axvline(linewidth=5,color='k', alpha=0.2)  # the vert line
        self.marker, = ax.plot([0],[0], marker="o", color="crimson", zorder=3) 
        self.x = x
        self.y = y
        self.txt = ax.text(0.7, 0.9, '')

    def mouse_move(self, event):
        if not event.inaxes: return
        x, y = event.xdata, event.ydata
        indx = np.searchsorted(self.x, [x])[0]
        print(indx)
        print('x1=',x,'y1=',y)
        print('self.x1=',self.x,'self.y1=',self.y)
        x = self.x[indx]
        y = self.y[indx]
        
        print('x2=',x,'y2=',y)
        print('self.x2=',self.x,'self.y2=',self.y)
        
        self.ly.set_xdata(x)
        self.marker.set_data([x],[y])
        self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
        self.txt.set_position((x,y))
        self.ax.figure.canvas.draw_idle()
df=pd.read_csv("./sample.csv")

df2=df[ df['L5v/L5v']==600e-9] #df2 contains a filtered version of df

text=[['Mn0_vov','Mn0_gmoverid','gm/Id vs vov','vov','gm/Id'],
        ['Mn0_gmoverid','Mn0_J','gm/Id vs current density','gm/Id','Current Density']
        #['Mn0_gmoverid','Mn0_gm'/'Mn0_gds','Intrinsic Gain vs gm/Id','gm/Id','gm/gds']
        
    ]

for item in text:   
    x=df2[item[0]]
    y=df2[item[1]]
    tlt=item[2]
    xx=item[3]
    yy=item[4]
    
    t=x.values.tolist()
    s=y.values.tolist()
    fig,ax=plt.subplots()
    cursor=SnaptoCursor(ax,t,s)
    plt.connect('motion_notify_event', cursor.mouse_move)
    ax.plot(x,y)
    
    ax.grid(b=True, which='major', color='#666666', linestyle='-')
    ax.minorticks_on()
    ax.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
    ax.set_xlabel(xx)
    ax.set_ylabel(yy)
    ax.set_title(tlt)
    #plt.xlim(5,20)

plt.show()
  • 1
    `searchsorted` looks up `[x]` (which is `event.xdata`) into the sorted array `self.x`. It assumes `self.x` is sorted from low to high. Maybe your array isn't sorted? Or it is sorted high to low? Or it isn't a numeric type? The `[0]` grabs the first element of the returned array (which should have length 1). Note that nowadays there is also a library [mplcursors](https://mplcursors.readthedocs.io/en/stable/) that creates such cursors in a simpler way. – JohanC Sep 14 '20 at 11:13
  • Well, I cannot install packages, so I must do that without using mplcursors. But why, would I need a sorted array? I mean, x,y are always changing when you move the mouse. – Pedro Cardoso Sep 14 '20 at 13:22
  • Hi, You are right. Please check my data on the link below. https://xfl.jp/JWVGSP – Pedro Cardoso Sep 14 '20 at 13:36
  • Code added. Please notice that I have a line in which I filter the data frame for a field that is not on the sample I've posted. But that should not be meaningful. The problem is that the cursor is simply stuck at 0, it doesn't move. – Pedro Cardoso Sep 14 '20 at 14:33
  • Your code doesn't fit your data. But note that for example the 'Mn0_gmoverid' isn't sorted, so probably the lineplot will look quite chaotic. Also note that the source of mplcursors is freely available and you can just copy it to your project without a need for installation. If you are running in a Jupyter notebook, you'll need `%matplotlib notebook` see [this post](https://stackoverflow.com/questions/43923313/canvas-mpl-connect-in-jupyter-notebook) – JohanC Sep 14 '20 at 14:54
  • I've downloaded the source code for mplcursors, but can't find the main file. Can you help me please? – Pedro Cardoso Sep 14 '20 at 15:08
  • 1
    You probably only need `_pick_info.py ` and `_mplcursors.py` and then `import ./_mplcursors as mplcursors`. The rest of the files is needed to create a pip-installable package. – JohanC Sep 14 '20 at 15:16
  • That's exactly that! Thanks a lot for your time and patience. Cheers, Pedro – Pedro Cardoso Sep 14 '20 at 17:29

0 Answers0