7

ベースマッププロットにポップアップボックスを作成する方法を知りたいです。ある場所にマウスを合わせると、ポップアップボックスが表示されます。

これは可能ですか?

4

1 に答える 1

31

はい、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()

うまくいけば、すべてがかなり読みやすいはずです。コードの概要は次のとおりです。

  • [ポイント、注釈]ペアのリストを作成します。デフォルトでは、注釈は表示されません。
  • マウスの動きが検出されるたびに呼び出される関数「on_move」を登録します
  • on_move関数は、各ポイントと注釈を繰り返し処理します。マウスがポイントの1つにある場合は、関連付けられている注釈を表示し、表示されていない場合は非表示にします。(containsメソッドはここに文書化されています

結果のスクリーンショット

于 2012-07-19T07:46:18.730 に答える