将光标添加到matplotlib [英] Add cursor to matplotlib

查看:45
本文介绍了将光标添加到matplotlib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此图显示了我要实现的目标:

This picture shows what I am trying to achieve:

我正在寻找一种解决方案,以将光标添加到 matplotlib 中的绘图行中.光标应该是可拖动的,但只能在绘制的线上移动.标签上应在轨迹上显示标记点的实际值.

I am searching for a solution to add a cursor to my plotted line in matplotlib. The cursor should be draggable, but should only move on the plotted line. A label shall display the actual value of the marked point on the trace.

我不知道将哪个对象用作此光标/标记.

I don't have an idea which object to use as this cursor/marker.

推荐答案

matplotlib 页面上有一个示例,您可以对其进行调整以在感兴趣的位置显示一个点.

There is an example on the matplotlib page, which you may adapt to show a point at the position of interest.

import matplotlib.pyplot as plt
import matplotlib.widgets as widgets
import numpy as np



class SnaptoCursor(object):
    def __init__(self, ax, x, y):
        self.ax = ax
        self.ly = ax.axvline(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]
        x = self.x[indx]
        y = self.y[indx]
        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()

t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*2*np.pi*t)
fig, ax = plt.subplots()

#cursor = Cursor(ax)
cursor = SnaptoCursor(ax, t, s)
cid =  plt.connect('motion_notify_event', cursor.mouse_move)

ax.plot(t, s,)
plt.axis([0, 1, -1, 1])
plt.show()

这篇关于将光标添加到matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆