将光标添加到Matplotlib中的绘图

2024-07-03 06:58:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将光标添加到Matplotlib,如下线程所示: Add cursor to matplotlib

我试图更改代码以使用存储在csv中的数据,但没有成功。 我使用pandas和“read_csv”导入文件内容,然后将数据帧/系列转换为列表

如果您能告诉我以下代码行的含义,我将不胜感激: indx=np.searchsorted(self.x[x])[0]

也许我错了,但随着鼠标的移动,我想我只需要抓取这些坐标,而不需要使用“searchsorted”功能,但我真的不知道

提前谢谢。 顺致敬意, 佩德罗

编辑日期:2020年9月14日

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

Tags: csvtextselfeventiddfaxitem