gpt4 book ai didi

python - matplotlib 小部件中的离散 slider

转载 作者:太空狗 更新时间:2023-10-29 20:27:28 25 4
gpt4 key购买 nike

基于 this solution ,我想制作一个只允许指定值的 slider , slider 本身也是离散的, slider 只有在选择了一个新点时才会移动(所以基本上是单选按钮的 slider 版本)。例如,如果我在当前点附近但不准确地单击,则 slider 不应更改并且绘图不应重绘。

我得到了很好的效果,但结果是滞后的:如果我在下面的示例中交替单击 1 和 10, slider 会正确更新,但移动点总是跳到以前的值。我该如何解决:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider

class ChangingPlot(object):
def __init__(self):
self.draw_counter = 0
x = np.logspace(0, 1, 10)

self.fig, self.ax = plt.subplots()
self.sliderax = self.fig.add_axes([0.2, 0.02, 0.6, 0.03],axisbg='yellow')
self.slider = DiscreteSlider(self.sliderax,'Value', 0, 10,\
allowed_vals=x, valinit=x[0])

self.slider.on_changed(self.update)

self.ax.plot(x, x, 'ro')
self.dot, = self.ax.plot(x[0], x[0], 'bo', markersize=18)
self.text = self.ax.text(2,8,str(self.draw_counter))

def update(self, value):
self.draw_counter += 1
self.dot.set_data([[value],[value]])
self.text.set_text(str(self.draw_counter)+' draws, value = '+str(value))

def show(self):
plt.show()

class DiscreteSlider(Slider):
"""A matplotlib slider widget with discrete steps."""
def __init__(self, *args, **kwargs):
"""
Identical to Slider.__init__, except for the new keyword 'allowed_vals'.
This keyword specifies the allowed positions of the slider
"""
self.allowed_vals = kwargs.pop('allowed_vals',None)
self.previous_val = kwargs['valinit']
Slider.__init__(self, *args, **kwargs)
if self.allowed_vals==None:
self.allowed_vals = [self.valmin,self.valmax]

def set_val(self, val):
discrete_val = self.allowed_vals[abs(val-self.allowed_vals).argmin()]
xy = self.poly.xy
xy[2] = discrete_val, 1
xy[3] = discrete_val, 0
self.poly.xy = xy
self.valtext.set_text(self.valfmt % discrete_val)
if self.drawon:
self.ax.figure.canvas.draw()
self.val = val
if self.previous_val!=discrete_val:
self.previous_val = discrete_val
if not self.eventson:
return
for cid, func in self.observers.iteritems():
func(discrete_val)

p = ChangingPlot()
p.show()

最佳答案

很好的例子,你需要调用Figure.canvas.draw()来刷新屏幕:

def update(self, value):
self.draw_counter += 1
self.dot.set_data([[value],[value]])
self.text.set_text(str(self.draw_counter)+' draws, value = '+str(value))
self.fig.canvas.draw() # <--- Add this line

关于python - matplotlib 小部件中的离散 slider ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23703105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com