matplotlib 中的条件按钮按下事件



我正在尝试编写一段代码,只有在选中复选框的情况下才会运行按钮单击事件。

更详细地说,按钮按下事件记录鼠标单击坐标,并在单击坐标处的绘图上绘制一条垂直红线。但是,我只希望在选中"开"复选框时运行它。

谁能帮我修复以下代码?

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)

我认为以下大致是这个问题所问的。这个问题中的代码有很多问题,我想我不能对所有问题进行评论,但一些主要的问题是:

  • 注册回调函数时,无法调用回调函数。而且您不能简单地使用一些自定义参数。 matplotlib 事件的参数是Events。
  • 您需要查询是否在回调函数中选中了该复选框。
  • 如果要显示新的红线,则需要绘制画布。
  • 对于二进制状态切换,单个复选框就足够了。否则,它就会变得非常复杂。
  • 您需要检查点击是否实际发生在轴内。这也要求复选框不在轴内,否则单击复选框也会生成一条线。

完整的代码。

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)

最新更新