Matplotlib底图:弹出框

And*_*way 7 python events popup matplotlib matplotlib-basemap

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

这可能吗?

pel*_*son 28

是的,这要归功于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()
Run Code Online (Sandbox Code Playgroud)

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

  • 创建[点,注释]对的列表,默认情况下,注释不可见
  • 注册一个函数"on_move",每次检测到鼠标移动时都要调用
  • 通过每个点和注释的on_move函数循环,如果鼠标现在是在点之一,使其相关的注释可见,如果不是,使其不可见.(此处记录了contains方法)

结果截图