问题描述
我想用鼠标单击画线,而键盘上的字母按钮在Matplotlib图形上画点。这是我到目前为止的代码。
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()
当您在图形上单击两次时,第一个功能应创建一行。第二个应该只是在您按图中的“ P”时创建一个点。任何帮助将不胜感激。
谢谢。
解决方法
请注意,我将用于绘制点的键形式从p
更改为x
,因为p
也是 pan 图形的快捷方式。
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)