温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python Matplotlib底图中鼠标滑过显示隐藏内容的实例代码

发布时间:2020-09-17 17:22:17 来源:脚本之家 阅读:144 作者:lisa丶 栏目:开发技术

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

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

python Matplotlib底图中鼠标滑过显示隐藏内容的实例代码

总结

以上所述是小编给大家介绍的python Matplotlib底图中鼠标滑过显示隐藏内容的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI