animation moving point error

匆匆过客 提交于 2021-01-28 02:08:40

问题


I am a beginner to Python. I'm trying to make an animation of a point moving in the horizontal direction. But, when I ran the code I received the below error:

TypeError: 'PathCollection' object is not iterable

I have no idea how to fix it.

#----------------------------------------------------------------------
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

Acc_11 = [1,2,3,4,6,7]
lenAcc11 = len(Acc_11)
Acc_12 = [2,2,2,2,2,2]

# Scatter plot
fig = plt.figure(figsize = (5,5))
ax = plt.axes()
scat = ax.scatter([],[])

#initial func
def init():
    return scat 
#animation func
def ani (i):

    for i in range(0,lenAcc11):
        acc_11 = Acc_11[i]
        print (acc_11)
        acc_11_pos = Acc_12[i]
        print (acc_11_pos)
    scat = scat.set_data(acc_11,acc_11_pos)
    return scat
ani = FuncAnimation(fig, ani, init_func = init, interval = 10, blit =True)

plt.show()             


#--------------------------------------------------------------------------

回答1:


Show all points

This shows all points:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

Acc_11 = [1,2,3,4,6,7]
Acc_12 = [2,2,2,2,2,2]

# Scatter plot
fig = plt.figure(figsize = (5,5))


def ani(coords):
     return plt.scatter([coords[0]],[coords[1]], color='g')

def frames():
    for acc_11_pos, acc_12_pos in zip(Acc_11, Acc_12):
        yield acc_11_pos, acc_12_pos

ani = FuncAnimation(fig, ani, frames=frames, interval=1000)

plt.show()

Show only one moving point

This shows only one point at a time:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

Acc_11 = [1,2,3,4,6,7]
Acc_12 = [2,2,2,2,2,2]

# Scatter plot
fig = plt.figure(figsize = (5,5))
axes = fig.add_subplot(111)
axes.set_xlim(min(Acc_11), max(Acc_11))
axes.set_ylim(min(Acc_12), max(Acc_12))

point, = axes.plot([Acc_11[0]],[Acc_12[0]], 'go')

def ani(coords):
    point.set_data([coords[0]],[coords[1]])
    return point

def frames():
    for acc_11_pos, acc_12_pos in zip(Acc_11, Acc_12):
        yield acc_11_pos, acc_12_pos

ani = FuncAnimation(fig, ani, frames=frames, interval=1000)

plt.show()


来源:https://stackoverflow.com/questions/35521545/animation-moving-point-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!