如何使用单击鼠标移动矩形补丁python3 [英] how can move rectangle patch with click mouse python3

查看:43
本文介绍了如何使用单击鼠标移动矩形补丁python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道当我用鼠标单击任何地方时如何移动矩形补丁吗?在固定在矩形下方的代码中,每次我用鼠标单击某个地方时,都只需将其移动,

I need to know how can I move the rectangle patch when I click anywhere with the mouse ? in the code below the rectangle is fixed I just need to move it every time I click with the mouse somewhere ,

import matplotlib.pyplot as plt
import matplotlib.patches as patches

x=y=0.1
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
patch= ax1.add_patch(patches.Rectangle((x, y), 0.5, 0.5,
    alpha=1, fill=None,label='Label'))


plt.show()

也许我需要使用"motion_notify_event"将鼠标连接到矩形,但是我不知道该如何使用该功能!

maybe i need to use "motion_notify_event" to connect mouse to rectangle but id'ont know how i can use this function !

我的第二个问题是如何使用 matplotlib 在图像上获得这种类型的矩形选择图标",或者如果可能的话自定义矩形补丁!

my second question is how to get this type of rectangle "selection icon" on the image with matplotlib or if possible to customize the rectangle patch !

先谢谢您

推荐答案

要移动矩形,您可以使用一个简单的函数,该函数通过 fig.canvas.mpl_connect('button_press_event' 连接到按钮按下事件", <function_name>) 并重新定义矩形的 x, y 原点坐标.我已经将它们移动了矩形的宽度和高度的一半,以便您单击的点将位于矩形的中心.

To move the rectangle around you can use a simple function that connects to a "button press event" via fig.canvas.mpl_connect('button_press_event', <function_name>) and re-defines the x, y origin coordinates of the rectangle. I have shifted those by half the width and height of the rectangle, so that the point you click on will be in its centre.

import matplotlib.pyplot as plt
import matplotlib.patches as patches

def on_press(event):
    xpress, ypress = event.xdata, event.ydata
    w = rect.get_width()
    h = rect.get_height()
    rect.set_xy((xpress-w/2, ypress-h/2))

    ax.lines = []   
    ax.axvline(xpress, c='r')
    ax.axhline(ypress, c='r')

    fig.canvas.draw() 

x = y = 0.1

fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
fig.canvas.mpl_connect('button_press_event', on_press)

rect = patches.Rectangle((x, y), 0.1, 0.1, alpha=1, fill=None, label='Label')

ax.add_patch(rect)

plt.show()

至于矩形的漂亮外观,请看一下matplotlib 补丁

As for the prettyfying of the rectangle, have a look at the matplotlib patches or the gallery and see if you find something suitable. I have added a crosshair with red lines as an alternative.

这篇关于如何使用单击鼠标移动矩形补丁python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆