【发布时间】:2015-03-29 16:02:21
【问题描述】:
我需要你的帮助。请考虑下面的代码,它使用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 类型,不提供这样的方法。
我的问题:如何以交互方式更新LineCollection?
【问题讨论】:
-
可能是
set_offsets或set_verts。 -
我无法让
set_offset或set_verts工作。set_segments确实有效,但您必须以 3D 数组的格式提供它,其中每个元素的格式为[[x, ymin], [x, ymax]]。
标签: python-3.x matplotlib python-interactive