簡體   English   中英

為什么 python list remove() 不適用於地塊列表?

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

我正在嘗試用 FuncAnimation 做一些 animation。 而不是 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')

這很好用。 但是,如果我使用 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')

由於 plot[0].remove() 導致代碼失敗,並出現以下錯誤:

remove() takes exactly one argument (0 given)

為什么會這樣?

斧頭。 scatter返回PathCollection object,它從父Collection繼承 function remove(self) 然而,斧頭。 plot返回Line2D對象的列表。 在 plot 的情況下,您正在從列表類型中調用 remove,但list.remove需要 1 個參數。

在分散的情況下,您正在從 PathCollection 類型中調用 remove,這不需要 arguments。

您可以在調用 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")

好的,這是您需要的行:

ax.lines.clear()

這是因為ax保留了它自己正在繪制的事物的列表,並且您對自己的列表所做的任何事情都不會影響它。 因此,此行刪除了所有行,然后您可以開始添加新行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM