我正在尝试编写一段仅在选中复选框时才运行按钮单击事件的代码。
更详细地,按下按钮的事件会记录鼠标单击的坐标,并在图形上在单击的坐标处绘制一条垂直的红线。但是,我只希望在选中“开”复选框时运行它。
有人可以帮助我修复以下代码吗?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
import ipywidgets as widgets
from ipywidgets import interactive
#mouse click function to store coordinates and plot vertical red line
def onclick(event):
if event == 'On':
global ix,iy
ix, iy = event.xdata, event.ydata
global click_count
click_count.append((ix,iy))
#plotting lines where clicks occur
if len(click_count) > 1:
ax1.axvline(x=ix, ymin=0, ymax=1, color = "red")
# assign global variable to access outside of function
global coords3
coords3.append((ix, iy))
# Disconnect after 12 clicks
if len(coords3) == 12:
fig.canvas.mpl_disconnect(cid)
plt.close(1)
return
#check box function
def func(label):
if label == 'On':
return 'On'
#plots the graph
x = range(0,10)
y = range(0,10)
fig = plt.figure(1)
ax1 = fig.add_subplot(111)
ax1.plot(x,y, color = "blue")
ax1.set_title('This is my graph')
#create the check box
ax2 = plt.axes([0.7, 0.05, 0.1, 0.075])
check_box= CheckButtons(ax2, ('On', 'Off'), (False, False))
#define check box function
check = check_box.on_clicked(func)
# calling out the click coordinates to a variable
coords3 = []
click_count = []
# Call click func
cid = fig.canvas.mpl_connect('button_press_event', onclick(check))
plt.show(1)
答案 0 :(得分:0)
我认为以下是这个问题的大致意思。问题中的代码有很多问题,我想我无法对所有问题都进行评论,但其中一些主要问题是:
Event
。完整代码。
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
#mouse click function to store coordinates and plot vertical red line
def onclick(event):
# Only use event within the axes.
if not event.inaxes == ax1:
return
# Check if Checkbox is "on"
if check_box.get_status()[0]:
ix, iy = event.xdata, event.ydata
coords3.append((ix,iy))
#plotting lines where clicks occur
if len(coords3) >= 1:
ax1.axvline(x=ix, ymin=0, ymax=1, color = "red")
fig.canvas.draw_idle()
# Disconnect after 12 clicks
if len(coords3) >= 12:
fig.canvas.mpl_disconnect(cid)
plt.close(fig)
#plots the graph
x = range(0,10)
y = range(0,10)
fig, ax1 = plt.subplots()
ax1.plot(x,y, color = "blue")
ax1.set_title('This is my graph')
#create the check box
ax2 = plt.axes([0.7, 0.05, 0.1, 0.075])
check_box = CheckButtons(ax2, ['On',], [False,])
# List to store coordinates
coords3 = []
# Callback to click func
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
print(coords3)