Python【Matplotlib】鼠标单击事件判断点击的是否为图例

直接上代码:

import matplotlib.pyplot as plt

# 创建一个简单的图表
fig, ax = plt.subplots()
line, = ax.plot([1, 2, 3], label='Line 1')
ax.legend(draggable=True)

# 获取图例对象
legend = ax.get_legend()

# 获取图例的边界框
legend_bbox = legend.get_window_extent()


def call_move(event):
    axtemp = event.inaxes
    mouse_x = event.x
    mouse_y = event.y
    print(f"鼠标_x={
     mouse_x}")
    print(f"鼠标_y={
     mouse_y}")

    if axtemp and axtemp.get_legend():
        legend_bbox = axtemp.get_legend().get_window_extent()
        left_bottom = legend_bbox.get_points()[0]
        right_top = legend_bbox.get_points()[1]

        if left_bottom[0] <= mouse_x <= right_top[0] and left_bottom[1] <= mouse_y <= right_top[1]:
            print("鼠标点击在图例矩形区域内。")
        else:
            print("鼠标点击在图例矩形区域外。")



fig.canvas.mpl_connect('button_press_event', call_move)

plt.show()

最近更新

  1. TCP协议是安全的吗?

    2023-12-19 10:32:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-19 10:32:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-19 10:32:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-19 10:32:03       20 阅读

热门阅读

  1. 获取 jira filter issue count 方法

    2023-12-19 10:32:03       44 阅读
  2. pnpm-lock.yaml、yarn.lock以及package-lock.json的区别

    2023-12-19 10:32:03       33 阅读
  3. uniapp数据缓存(存储/获取/移出)

    2023-12-19 10:32:03       46 阅读
  4. ubuntu添加路由

    2023-12-19 10:32:03       37 阅读
  5. python爬虫---urllib

    2023-12-19 10:32:03       38 阅读
  6. Wireshark在云计算中的应用

    2023-12-19 10:32:03       30 阅读