Python 3.x 在交互式绘图中更新pyplot.vline

Python 3.x 在交互式绘图中更新pyplot.vline,python-3.x,matplotlib,python-interactive,Python 3.x,Matplotlib,Python Interactive,我需要你的帮助。请考虑下面的代码,它使用 Pylab < /代码>在 IPython < /代码>中绘制一个正弦波。轴下方的滑块使用户能够交互调整正弦频率 %pylab # setup figure fig, ax = subplots(1) fig.subplots_adjust(left=0.25, bottom=0.25) # add a slider axcolor = 'lightgoldenrodyellow' ax_freq = axes([0.3, 0.13, 0.5, 0.0

我需要你的帮助。请考虑下面的代码,它使用<代码> Pylab < /代码>在<代码> IPython < /代码>中绘制一个正弦波。轴下方的滑块使用户能够交互调整正弦频率

%pylab
# setup figure
fig, ax = subplots(1)
fig.subplots_adjust(left=0.25, bottom=0.25)

# add a slider
axcolor = 'lightgoldenrodyellow'
ax_freq = axes([0.3, 0.13, 0.5, 0.03], axisbg=axcolor)
s_freq = Slider(ax_freq, 'Frequency [Hz]', 0, 100, valinit=a0)

# plot 
g = linspace(0, 1, 100)
f0 = 1
sig = sin(2*pi*f0*t)
myline, = ax.plot(sig)

# update plot
def update(value):
    f = s_freq.val
    new_data = sin(2*pi*f*t)
    myline.set_ydata(new_data)     # crucial line
    fig.canvas.draw_idle()

s_freq.on_changed(update)
我需要将信号绘制为垂直线,从
t
中每个点的振幅到x轴。因此,我的第一个想法是在第15行中使用
vlines
而不是
plot

myline = ax.vlines(range(len(sig)), 0, sig)
此解决方案适用于非交互式情况。问题是,
plot
返回一个
matplotlib.lines.Line2D
对象,该对象提供了交互式更新数据的
set_ydata
方法。
vlines
返回的对象属于
matplotlib.collections.LineCollection
类型,不提供此类方法。
我的问题:如何以交互方式更新
行集合

使用
@Aaron Voelker
关于使用
设置段并将其封装在函数中的注释:

def update_vlines(*, h, x, ymin=None, ymax=None):
    seg_old = h.get_segments()
    if ymin is None:
        ymin = seg_old[0][0, 1]
    if ymax is None:
        ymax = seg_old[0][1, 1]

    seg_new = [np.array([[xx, ymin],
                         [xx, ymax]]) for xx in x]

    h.set_segments(seg_new)
hlines的模拟功能

def update_hlines(*, h, y, xmin=None, xmax=None):
    seg_old = h.get_segments()
    if xmin is None:
        xmin = seg_old[0][0, 0]
    if xmax is None:
        xmax = seg_old[0][1, 0]

    seg_new = [np.array([[xmin, yy],
                         [xmax, yy]]) for yy in y]

    h.set_segments(seg_new)

我将在这里给出
vline
的示例

若你们有多条生产线,那个么这个解决方案是完美的。您也可能更喜欢一个班轮:

myline.set_段([np.数组([[x,x_最小值],[x,x_最大值]]),用于xx中的x])
如果只需要更新最大值,则可以执行以下操作:

def更新\u最大值(vline):
vline[:,1]=最小x_,最大x_
回程线
myline.set_segments(列表(映射(更新_maxs,x.get_segments()))

这个例子也很有用:

可能是
设置偏移量
设置顶点
。我无法让
设置偏移量
设置顶点
工作<代码>设置_段确实有效,但必须以3D数组的格式提供,其中每个元素的形式为
[[x,ymin],[x,ymax]