Issue
I want to use the mouse clicks to draw lines, while a letter button on the keyboard to draw a point on a Matplotlib figure. This is the code I have so far.
def onclick(event):
global current_coords
if event.inaxes:
current_coords.append((event.xdata, event.ydata))
if len(current_coords) == 2:
ax.plot([current_coords[0][0], current_coords[1][0]],
[current_coords[0][1], current_coords[1][1]], 'ro-')
coords.append([current_coords[0], current_coords[1]])
current_coords[:] = []
fig.canvas.draw()
def onkey(event):
global current_coords1
if keyboard.is_pressed('p'):
current_coords1.append((event.xdata, event.ydata))
if len(current_coords1) == 1:
ax.plot([current_coords1[0][0], current_coords1[1][0]], 'bo-')
coords1.append([current_coords1[0], current_coords1[1]])
current_coords1[:] = []
fig.canvas.draw()
cid = fig.canvas.mpl_connect('button_press_event', onclick)
cid1 = fig.canvas.mpl_connect('button_press_event', onkey)
plt.show()
The first function should create a line when you click twice on the figure. The second should just create a dot when you press "P" on the figure. Any help would be greatly appreciated.
Thanks in advance.
Solution
Note that I changed the key form p
to x
for drawing points as p
is also the shortcut to pan the graph.
import matplotlib.pyplot as plt
# %matplotlib widget # for jupyter notebooks (pip install ipympl)
fig, ax = plt.subplots()
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
global current_coords
current_coords = []
def onclick(event):
global current_coords
if event.inaxes:
current_coords.append((event.xdata, event.ydata))
if len(current_coords) == 2:
ax.plot([current_coords[0][0], current_coords[1][0]],
[current_coords[0][1], current_coords[1][1]], 'ro-')
current_coords[:] = []
fig.canvas.draw()
def onkey(event):
print(event.key)
if event.key == 'x':
if event.xdata is not None and event.ydata is not None:
ax.plot(event.xdata, event.ydata, 'bo-')
fig.canvas.draw()
cid1 = fig.canvas.mpl_connect('button_press_event', onclick)
cid2 = fig.canvas.mpl_connect('key_press_event', onkey)
Answered By - scleronomic
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.