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()