I have a dataframe that includes position data from all 9 players on a baseball field including the hitter throughout a given play as well as the ball trajectory. I need some help with figuring out possibly why my animation is not working. The code below plots an instance of the plot, but it doesn’t show a continuous animation. In other words, it should show dots moving continuously. Here is my code:
import pandas as pd
from sportypy.surfaces import MiLBField
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
# The dimensions are not exactly like this but this is an example if you need something to go off of
num_rows = 50
data = {
'game_str': ['game_01'] * num_rows,
'play_id': [10] * num_rows,
'timestamp': np.random.randint(180000, 181000, size=num_rows),
'player_position': np.random.randint(1, 11, size=num_rows),
'field_x': np.random.uniform(-150, 150, size=num_rows),
'field_y': np.random.uniform(-150, 150, size=num_rows),
'ball_position_x': np.random.uniform(0.0, 2.0, size=num_rows),
'ball_position_y': np.random.uniform(0.0, 300.0, size=num_rows),
'ball_position_z': np.random.uniform(0.0, 10.0, size=num_rows)
}
df = pd.DataFrame(data).sort_values(by='timestamp')
field = MiLBField()
def update(frame):
frame_data = df[df['timestamp'] <= frame]
players = frame_data[['field_x', 'field_y']]
balls = frame_data[['ball_position_x', 'ball_position_y']]
plt.clf()
field.draw(display_range='full')
p = field.scatter(players['field_x'], players['field_y'])
b = field.scatter(balls['ball_position_x'], balls['ball_position_y'])
return p, b
fig = plt.figure()
ani = FuncAnimation(fig, update, frames=np.linspace(df['timestamp'].min(), df['timestamp'].max(), num=100), blit=True)
plt.show()
I would like it to output a baseball field with the scatter points moving as time increases.
Newman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.