Python matplotlib如何清除上一个绘图点?

2024-04-25 02:05:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码如下所示。我希望在动画过程中,每一帧只画一个点,它应该在线的头部,但实际上所有先前的点都显示出来了。似乎每次plt都只在图纸上加点,如何改变这一点,使其清楚地显示出前一点?all the red point are shown which is not wanted,下面列出数据框供参考。在

0.0 0.0

0.26 186780.0

0.27 197556.0

0.53 519439.0

0.54 533579.0

0.8 946285.0

0.81 960288.0

1.07 1306550.0

1.08 1320020.0

1.34 1642600.0

from matplotlib import pyplot as plt
from matplotlib import animation,rc
import pandas as pd

fig = plt.figure()
df=pd.read_csv('radialforce.csv', sep=';',skipinitialspace=True,na_values=" 
NaN")
df.dropna(axis="columns", how="any", inplace=True)
df.columns.values[1] = 'Y'


def animate(n):
    plt.plot(df['X'][:n], df['Y'][:n],color='g',lw='0.5')
    plt.scatter(df['X'][n], df['Y'][n],10,facecolor='r',edgecolor='r')    
    return fig

anim = animation.FuncAnimation(fig, animate,frames=len(df['X']), 
interval=100)
plt.show()

Tags: columnscsv代码fromimporttruedfmatplotlib
1条回答
网友
1楼 · 发布于 2024-04-25 02:05:33

你不想每次迭代都重画所有的东西。相反,您需要更新线和散点。在

from matplotlib import pyplot as plt
from matplotlib import animation,rc
import pandas as pd

fig = plt.figure()
df=pd.read_csv(...)
df.dropna(axis="columns", how="any", inplace=True)
df.columns.values[1] = 'Y'

line, = plt.plot(df['X'][:1], df['Y'][:1],color='g',lw='0.5')
scatter = plt.scatter(df['X'][0], df['Y'][0],10,facecolor='r',edgecolor='r')    

def animate(n):
    x,y=df['X'][:n+1], df['Y'][:n+1]
    line.set_data(x,y)
    scatter.set_offsets([df['X'][n], df['Y'][n]])
    plt.gca().relim()
    plt.gca().autoscale_view()

anim = animation.FuncAnimation(fig, animate,frames=len(df['X']), interval=100)
plt.show()

enter image description here

相关问题 更多 >