简体   繁体   English

为什么 python list remove() 不适用于地块列表?

[英]Why doesn't python list remove() work for list of plots?

I'm trying to do some animation with FuncAnimation.我正在尝试用 FuncAnimation 做一些 animation。 Instead of using.set_data() I'm using this alternative structure:而不是 using.set_data() 我正在使用这种替代结构:

def update_plot(frame, y, plot):
    plot[0].remove()
    plot[0] = ax.scatter(np.sin(y[frame,0]),-np.cos(y[frame,0]), color = "orange")

#(...)

# Initial
plot = [ax.scatter(np.sin(y[0,0]),-np.cos(y[0,0]), color = "orange")]

# Animate
animate = animation.FuncAnimation(fig, update_plot, nmax, fargs = (y, plot))
animate.save('pendulum.gif',writer='imagemagick')

This works well.这很好用。 However, if I use ax.plot() instead of ax.scatter():但是,如果我使用 ax.plot() 而不是 ax.scatter():

def update_plot(frame, y, plot):
    plot[0].remove()
    plot[0] = ax.plot(np.sin(y[frame,0]),-np.cos(y[frame,0]),'o', color = "orange")

# Initial
plot = [ax.plot(np.sin(y[0,0]),-np.cos(y[0,0]),'o', color = "orange")]

# Animate
animate = animation.FuncAnimation(fig, update_plot, nmax, fargs = (y, plot))
animate.save('pendulum.gif',writer='imagemagick')

the code fails because of the plot[0].remove() with the following error:由于 plot[0].remove() 导致代码失败,并出现以下错误:

remove() takes exactly one argument (0 given)

Why is that the case?为什么会这样?

ax.斧头。 scatter returns PathCollection object, it inherits function remove(self) from parent Collection . scatter返回PathCollection object,它从父Collection继承 function remove(self) However, ax.然而,斧头。 plot returns a list of Line2D objects. plot返回Line2D对象的列表。 In the case of plot, you are calling remove from a list type, but list.remove needs 1 argument.在 plot 的情况下,您正在从列表类型中调用 remove,但list.remove需要 1 个参数。

In the case of scatter, you're are calling remove from PathCollection type, that doesn't need arguments.在分散的情况下,您正在从 PathCollection 类型中调用 remove,这不需要 arguments。

You can check the type before calling remove, using isinstance to check if plot is type list or PathCollection.您可以在调用 remove 之前检查类型,使用 isinstance 检查 plot 是类型列表还是 PathCollection。

def update_plot(frame, y, plot):
    if isinstance(plot[0], list):
        plot[0][0].remove()
        plot[0][0] = ax.plot(np.sin(y[frame,0]),-np.cos(y[frame,0]),'o', color = "orange")
    else:
        plot[0].remove()
        plot[0] = ax.scatter(np.sin(y[frame,0]),-np.cos(y[frame,0]), color = "orange")

OK, so here is the line you need:好的,这是您需要的行:

ax.lines.clear()

This is because ax retains its own list of things it is plotting, and anything you do to your own lists won't affect that.这是因为ax保留了它自己正在绘制的事物的列表,并且您对自己的列表所做的任何事情都不会影响它。 So, this line removes all the lines, and then you can start adding new ones.因此,此行删除了所有行,然后您可以开始添加新行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM