0

我创建了一个交互式散点图,使用bqplot您可以拖动点的位置(使用enable_move=True)。

我不希望用户将点拖到 y=x 线上方。如果他们这样做了,我希望该点恢复到最近的位置。

问题是我不确定如何在这里避免无限递归。

散点图需要知道它的点何时移动,以便检查移动并可能回弹。然而,当它开始回弹时,这种(点位置的)变化似乎触发了同样的回调。

谁能告诉我处理这个基本问题的“正确”方法?

import bqplot.pyplot as plt
import numpy as np

def on_point_move(change, scat):
    if np.any(newx < scat.y):
        scat.x = change['old']
    
fig = plt.figure(animation_duration=400)
xs = 1.0*np.arange(3) # make sure these are floats
ys = 1.0*np.arange(3)
scat = plt.scatter(xs, ys, colors=['Red'], default_size=400, enable_move=True)
scat.observe(lambda change: on_point_move(change, scat), names=['x'])
fig
4

1 回答 1

1

您可以在 on_point_move 函数中暂时禁用观察。我也稍微改变了逻辑。

import bqplot.pyplot as plt
import numpy as np

def on_point_move(change):
    if np.any(scat.x < scat.y):
        scat.unobserve_all()
        if change['name'] == 'x':
            scat.x = change['old']
        elif change['name'] == 'y':
            scat.y = change['old']
        scat.observe(on_point_move, names=['x','y'])
    

fig = plt.figure(animation_duration=400)
xs = 1.0*np.arange(3) # make sure these are floats
ys = 1.0*np.arange(3)
scat = plt.scatter(xs, ys, colors=['Red'], default_size=400, enable_move=True)
scat.observe(on_point_move, names=['x','y'])

fig
于 2020-11-30T12:19:59.213 回答