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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值