简体   繁体   中英

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

I'm trying to do some animation with FuncAnimation. Instead of using.set_data() I'm using this alternative structure:

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():

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:

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 . However, ax. plot returns a list of Line2D objects. In the case of plot, you are calling remove from a list type, but list.remove needs 1 argument.

In the case of scatter, you're are calling remove from PathCollection type, that doesn't need arguments.

You can check the type before calling remove, using isinstance to check if plot is type list or 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. So, this line removes all the lines, and then you can start adding new ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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