How Can Move Rectangle Patch With Click Mouse 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 th
Solution 1:
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()
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.
Post a Comment for "How Can Move Rectangle Patch With Click Mouse Python3"