【问题标题】:python - how can I display cursor on all axes vertically but only on horizontally on axes with mouse pointer on toppython - 如何在所有轴上垂直显示光标,但仅在水平轴上显示光标,鼠标指针在顶部
【发布时间】:2022-01-20 04:30:22
【问题描述】:

我希望光标在所有轴上垂直可见,但仅对鼠标指针所在的轴水平可见。

这是我目前正在使用的代码。

import matplotlib.pyplot as plt
from matplotlib.widgets import MultiCursor

fig = plt.figure(facecolor='#07000d')

ax1 = plt.subplot2grid((2,4), (0,0), rowspan=1,colspan=4, axisbg='#aaaaaa')
ax2 = plt.subplot2grid((2,4), (1,0), rowspan=1,colspan=4, axisbg='#aaaaaa')

multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=.5, horizOn=True, vertOn=True)
plt.show()

这就是我所拥有的。我想要的是让水平光标只对鼠标指针所在的轴可见,但垂直对两者都可见。

【问题讨论】:

    标签: python matplotlib mouse-cursor


    【解决方案1】:

    所以我想出了一个解决方案。我使用封装在类中的鼠标事件制作了自己的自定义光标。效果很好。您可以将轴添加到数组/列表中。

    import numpy as np
    import matplotlib.pyplot as plt
    
    class CustomCursor(object):
    
    def __init__(self, axes, col, xlimits, ylimits, **kwargs):
        self.items = np.zeros(shape=(len(axes),3), dtype=np.object)
        self.col = col
        self.focus = 0
        i = 0
        for ax in axes:
            axis = ax
            axis.set_gid(i)
            lx = ax.axvline(ymin=ylimits[0],ymax=ylimits[1],color=col)
            ly = ax.axhline(xmin=xlimits[0],xmax=xlimits[1],color=col)
            item = list([axis,lx,ly])
            self.items[i] = item
            i += 1
    def show_xy(self, event):
        if event.inaxes:
            self.focus = event.inaxes.get_gid()
            for ax in self.items[:,0]:
                self.gid = ax.get_gid()                                     
                for lx in self.items[:,1]:
                    lx.set_xdata(event.xdata)
                if event.inaxes.get_gid() == self.gid:
                    self.items[self.gid,2].set_ydata(event.ydata)
                    self.items[self.gid,2].set_visible(True)
        plt.draw()
    
    def hide_y(self, event):
        for ax in self.items[:,0]:
            if self.focus == ax.get_gid():
                self.items[self.focus,2].set_visible(False)
    
    
    
    
    if __name__ == '__main__':
    fig = plt.figure(facecolor='#07000d')
    ax1 = plt.subplot2grid((2,4), (0,0), rowspan=1,colspan=4, axisbg='#aaaaaa')
    ax2 = plt.subplot2grid((2,4), (1,0), rowspan=1,colspan=4, axisbg='#aaaaaa')
    
    cc = CustomCursor([ax1,ax2], col='red', xlimits=[0,100], ylimits=[0,100], markersize=30,)
    fig.canvas.mpl_connect('motion_notify_event', cc.show_xy)
    fig.canvas.mpl_connect('axes_leave_event', cc.hide_y)
    
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 1970-01-01
      • 2012-03-30
      • 2021-08-28
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      相关资源
      最近更新 更多