gpt4 book ai didi

python - 如何制作移动散点的动画

转载 作者:太空宇宙 更新时间:2023-11-03 16:54:45 24 4
gpt4 key购买 nike

我是Python初学者。我正在尝试制作一个沿水平方向移动的点的动画。但是,当我运行代码时,我收到以下错误:

TypeError: 'PathCollection' object is not iterable

我不知道如何解决它。

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


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

最佳答案

显示所有点

这显示了所有要点:

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

enter image description here

仅显示一个移动点

一次仅显示一个点:

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

enter image description here

来自数据框而不是列表

  • 前面的两个选项都可以很好地处理数据框。将 Acc_11 = 设置为 x 轴的数据帧列,将 Acc_12 = 设置为 y 轴的数据帧列。
import seaborn as sns

# sample dataframe
tips = sns.load_dataset('tips')

x = tips.total_bill
y = tips.tip

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

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


def frames():
for x_pos, y_pos in zip(x, y):
yield x_pos, y_pos


ani = animation.FuncAnimation(fig, ani, frames=frames, interval=1000)
ani.save('animation2.gif', fps=30)

plt.show()

enter image description here

关于python - 如何制作移动散点的动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35521545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com