我正在编写测量程序,matplotlib用于显示测量值。我想出了如何为单个情节做到这一点,即
x=[0,1,2]
y=[3,5,7]
set_xdata(x)
set_ydata(y)
每次x和y更改时,我都会调用set_xdata
和set_ydata
并刷新图表。
但是,我想动态n
y值与单个x值,即
x=[0,1,2]
y=[[3,5,7],[4,6,8],[5,7,9]]
是否可以这样做,知道n
(y个图的数量)?
编辑:
我对两件事感兴趣:
答案 0 :(得分:2)
简而言之:您必须为每个“情节”创建一个Line2D
个实例。
稍微详细一点:
正如你用一行完成的那样,你也可以用多行来做同样的事情:
import matplotlib.pyplot as plt
# initial values
x = [0,1,2]
y = [[3,5,7],[4,6,8],[5,7,9]]
# create the line instances and store them in a list
line_objects = list()
for yi in y:
line_objects.extend(plt.plot(x, yi))
# new values with which we want to update the plot
x = [1,2,3]
y = [[4,6,8],[5,7,9],[6,8,0]]
# update the y values dynamically (without recreating the plot)
for yi, line_object in zip(y, line_objects):
line_object.set_xdata(x)
line_object.set_ydata(yi)
不是真的。但是,您只需拨打一次Line2D
即可创建多个plot
个对象:
line_objects = plt.plot(x, y[0], x, y[1], x, y[2])
这也是plot
始终返回列表的原因。
如果您经常这样做,可能有助于使用辅助函数:
E.g:
def plot_multi_y(x, ys, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
return [ax.plot(x, y, **kwargs)[0] for y in ys]
def update_multi_y(line_objects, x, ys):
for y, line_object in zip(ys, line_objects):
line_object.set_xdata(x)
line_object.set_ydata(y)
然后你可以使用:
# create the lines
line_objects = plot_multi_y(x, y)
#update the lines
update_multi_y(line_objects, x, y)