python Matplotlib底图中鼠标滑过显示隐藏内容

      在使用Matplotlib画图过程中,有些内容必须鼠标点击或者划过才可以显示,这个问题可以依赖于annotate(s='str' ,xy=(x,y) ,xytext=(l1,l2) ,..)这个函数,其中s 为注释文本内容 , xy 为被注释的坐标点, xytext 为注释文字的坐标位置,其他参数可自行百度哈。当鼠标滑过时候,将其设置为可见,默认情况下为隐藏。下面是一个小例子:

# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt

fig = plt.figure()
po_annotation = []
for i in range(0, 10):
    x = i
    y = x**2
    point, = plt.plot(x, y, 'o')
    annotation = plt.annotate(('x='+str(x), 'y='+str(y)), xy=(x+0.1, y+0.1), xycoords='data', xytext=(x+0.7, y+0.7),
                                textcoords='data', horizontalalignment="left",
                                arrowprops=dict(arrowstyle="simple",connectionstyle="arc3,rad=-0.1"),
                                bbox=dict(boxstyle="round", facecolor="w",edgecolor="0.5", alpha=0.9)
                                )
    annotation.set_visible(False)
    po_annotation.append([point, annotation])

def on_move(event):
    visibility_changed = False
    for point, annotation in po_annotation:
        should_be_visible = (point.contains(event)[0] == True)
        # print(point.contains(event)[0])

        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函数遍历每个点和注释,如果鼠标现在位于其中一个点上,则使其关联的注释可见,如果不是,则使其不可见。

运行出来的效果为: 当鼠标滑过时,可以显示其相应坐标:


恩......,参考自http://osask.cn/front/ask/view/512391


猜你喜欢

转载自blog.csdn.net/weixin_42341986/article/details/80662076
今日推荐