【问题标题】:Matplotlib basemap: Popup boxMatplotlib 底图:弹出框
【发布时间】:2012-07-17 06:03:35
【问题描述】:

我想知道如何在底图绘图中创建一个弹出框。当我将鼠标悬停在某个位置上时,它应该会触发弹出框。

这可能吗?

【问题讨论】:

    标签: python events popup matplotlib matplotlib-basemap


    【解决方案1】:

    是的,这要归功于 matplotlib 的事件处理框架。我找不到一个已经写好的例子来做你特别感兴趣的事情,所以我写了一个(我会提出包含在 matplotlib 源代码中)。

    我会仔细阅读http://matplotlib.sourceforge.net/users/event_handling.html 以最好地了解正在发生的事情。请注意,虽然听起来完美的解决方案“pick_event”是针对鼠标点击而不是针对鼠标悬停事件,并且在这种情况下不起作用。

    我的代码可以很好地客观化,应该是这样的:

    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax = plt.axes()
    
    
    points_with_annotation = []
    for i in range(10):
        point, = plt.plot(i, i, 'o', markersize=10)
    
        annotation = ax.annotate("Mouseover point %s" % i,
            xy=(i, i), xycoords='data',
            xytext=(i + 1, i), 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)
            )
        # by default, disable the annotation visibility
        annotation.set_visible(False)
    
        points_with_annotation.append([point, annotation])
    
    
    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()
    
    on_move_id = fig.canvas.mpl_connect('motion_notify_event', on_move)
    
    plt.show()
    

    希望一切都应该是相当可读的。代码的高级概述如下:

    • 创建 [point, annotation] 对的列表,默认情况下注释不可见
    • 注册一个函数“on_move”,在每次检测到鼠标移动时调用
    • on_move 函数遍历每个点和注释,如果鼠标现在位于其中一个点上,则使其关联的注释可见,如果不是,则使其不可见。 (包含方法是documented here

    【讨论】:

    • 啊可爱,谢谢@pelson 的代码和解释。所以这意味着没有直接的事件处理程序可以将鼠标悬停在绘图上的某个位置上。它需要间接完成。
    • 没有。您可以在 on_move 函数中访问鼠标事件的 x 和 y 坐标。从那你可以做任何事情。在我的情况下,我查看了所有艺术家并确定是否有任何包含鼠标位置,但你可以同样更新单个注释实例的位置给定 x 和 y。
    • 是的,你在这一点上是对的,但我一直在寻找像“hover_event”这样的事件向特定艺术家注册回调之类的东西,这就是我所说的直接事件
    • 对。不,我不知道。必须能够打开将是一个很好的功能(但如果它总是检查可能会影响性能......)。希望对您有所帮助。
    • 感谢@pelson 提供的解决方案。如果您知道如果 ax 是极坐标图,为什么注释会表现得很奇怪,我只是好奇。我正在使用您的确切解决方案在我的极坐标图上添加注释,但是,实际上只显示了注释的子集(即使它们都已创建并且正在对 onmove 事件作出反应)。我在这里发布了一个问题 - stackoverflow.com/questions/15649887/…(简化了事件处理程序)。提前感谢您提供的任何帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    相关资源
    最近更新 更多