【问题标题】:Python and Matplotlib and Annotations with Mouse HoverPython 和 Matplotlib 以及鼠标悬停注释
【发布时间】:2012-09-16 14:05:23
【问题描述】:

当我单击 Basemap Matplotlib Plot 中的一个点时,我目前正在使用此代码在地图上弹出注释。

dcc = DataCursor(self.figure.gca())
self.figure.canvas.mpl_connect('pick_event',dcc)
plot_handle.set_picker(5)
self.figure.canvas.draw()

class DataCursor(object):

    import matplotlib.pyplot as plt

    text_template = 'x: %0.2f\ny: %0.2f' 
    x, y = 0.0, 0.0 
    xoffset, yoffset = -20 , 20
    text_template = 'A: %s\nB: %s\nC: %s'


    def __init__(self, ax): 
        self.ax = ax 
        self.annotation = ax.annotate(self.text_template,  
                xy=(self.x, self.y), xytext=(0,0),
                textcoords='axes fraction', ha='left', va='bottom', fontsize=10,
                bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=1), 
                arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0') 
                ) 
        self.annotation.set_visible(False)
        self.annotation.draggable()


    def __call__(self, event):

        self.event = event 
        self.x, self.y = event.mouseevent.xdata, event.mouseevent.ydata

        if self.x is not None:
            glim = pickle.load(open("ListA.py","rb"))
            tlim = pickle.load(open("ListB.py","rb"))
            vlim = pickle.load(open("ListC.py","rb"))
            a = glim[event.ind[0]] # ['Name'][event.ind[0]]
            b = tlim[event.ind[0]]
            c = vlim[event.ind[0]]
            temp_temp=self.text_template % (a, b, c)
            if temp_temp == self.annotation.get_text() and self.annotation.get_visible(): 
                self.annotation.set_visible(False) 
                event.canvas.draw() 
                return 
            self.annotation.xy = self.x, self.y
            self.annotation.set_text(self.text_template % (a, b, c))
            self.annotation.set_visible(True)

            event.canvas.draw()

我想知道的是,如何使用鼠标悬停而不是单击某个点来显示注释?

我见过“motion_notify_event”,但是当我在绘图区域周围移动鼠标时,代码似乎出错了。有什么想法吗?

【问题讨论】:

    标签: python annotations matplotlib wxpython matplotlib-basemap


    【解决方案1】:

    看看this questiondemo

    from matplotlib.pyplot import figure, show
    import numpy as npy
    from numpy.random import rand
    
    
    if 1: # picking on a scatter plot (matplotlib.collections.RegularPolyCollection)
    
        x, y, c, s = rand(4, 100)
        def onpick3(event):
            ind = event.ind
            print 'onpick3 scatter:', ind, npy.take(x, ind), npy.take(y, ind)
    
        fig = figure()
        ax1 = fig.add_subplot(111)
        col = ax1.scatter(x, y, 100*s, c, picker=True)
        #fig.savefig('pscoll.eps')
        fig.canvas.mpl_connect('pick_event', onpick3)
    
    show()
    

    【讨论】:

    • 我已经看到了这两个链接,但是我不确定如何以我当前的格式实现它们。我也没有看到“pick_event”是一个不可点击的动作?
    • 我接受这个答案,但这不是正确的答案。但是,Root 确实链接了另一个链接这个 [question] (stackoverflow.com/questions/4453143/…) 的问题,它提供了悬停和显示注释的正确方法。注意:我仍然使用注释而不是 wx.tooltip。效果很好!
    【解决方案2】:
    from mpl_toolkits.basemap import Basemap
    import matplotlib.pyplot as plt
    
    lat = 20.5937
    lon = 78.9629
    points_with_annotation = list()
    
    #Event is set for any movement and annotations are set to visible when on points with anotation
    def on_move(event):
        visibility_changed = False
        for point, annotation in points_with_annotation:
            should_be_visible = (point.contains(event)[0] == True)
    
            if should_be_visible != annotation.get_visible():
                visibility_changed = True
                annotation.set_visible(should_be_visible)
    
        if visibility_changed:        
            plt.draw()
    
    
    fig = plt.figure()
    ax = plt.axes()
    
    m = Basemap(projection='mill', llcrnrlat=-90, llcrnrlon=-180, urcrnrlat=90, urcrnrlon=180, resolution='c')
    m.fillcontinents(color='white', lake_color='white')
    m.drawcoastlines(linewidth=0.5, color='k')
    m.drawcountries(linewidth=0.5, color='k')
    m.drawmapboundary(fill_color='white')
    
    xpt, ypt = m(lon,lat)
    point, = m.plot(xpt, ypt, marker='o', markersize=5, alpha=0.85, visible=True)
    annotation = ax.annotate("Lat: %s Lon: %s" % (lat,lon), 
        xy=(xpt, ypt), xycoords='data',
        xytext=(xpt + 1, ypt), textcoords='data',
        horizontalalignment="left",
        arrowprops=dict(arrowstyle="simple",
        connectionstyle="arc3,rad=-0.2"),
        bbox=dict(boxstyle="round", facecolor="w", 
        edgecolor="0.5", alpha=0.9)
            )
    
    
    annotation.set_visible(False)
    points_with_annotation.append([point, annotation])
    on_move_id = fig.canvas.mpl_connect('motion_notify_event', on_move)
    plt.show()
    

    这是在地图上绘制坐标并在悬停期间启用弹出窗口的代码。我从这个问题的答案中得到了on_move 事件的代码:Matplotlib basemap: Popup box 希望这会有所帮助。

    【讨论】:

    • 如果我们能解释一下为什么我们应该像这样编写代码而不是粘贴代码并说你从某个地方得到它,那就太好了。如果他们将来回答您的问题,这也会对其他人有所帮助。
    • @rsz 抱歉。已编辑。
    猜你喜欢
    • 2020-01-23
    • 1970-01-01
    • 2011-05-26
    • 2017-10-14
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 2011-12-01
    • 2011-08-04
    相关资源
    最近更新 更多