I’m aiming to animate a scatter plot using the df below. I’m trying to pass the plot and groups function to the animate function. I’m trying to return the values from each function are pass them to subsequent functions but I’m getting aNameError as these values aren't being registered.
The script works if I remove the plot and groups functions and pass objects to animate from the global workspace but then I have to write these out all the time. Rather than house in separate functions.
import pandas as pd import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl from matplotlib import animation df1 = pd.DataFrame({ 'Time' : [1,1,1,2,2,2,3,3,3], 'GroupA_X' : [3, 4, 5, 2, 5, 6, 1, 6, 7], 'GroupA_Y' : [2, 4, 5, 2, 5, 5, 2, 6, 5], 'GroupB_X' : [2, 5, 3, 2, 4, 2, 2, 3, 1], 'GroupB_Y' : [2, 4, 3, 3, 3, 4, 4, 2, 5], }) def plot(): fig, ax = plt.subplots() ax.grid(False) xy = 0,0 Oval = mpl.patches.Ellipse(xy, 160, 130, lw = 2, edgecolor = 'black', color = 'blue', alpha = 0.2) ax.add_patch(Oval) return fig, ax def groups(): plot() Group_A = df1[['Time','GroupA_X','GroupA_Y']] Group_B = df1[['Time','GroupB_X','GroupB_Y']] GA_X = np.array(Group_A.groupby(['Time'])['GroupA_X'].apply(list)) GA_Y = np.array(Group_A.groupby(['Time'])['GroupA_Y'].apply(list)) GB_X = np.array(Group_B.groupby(['Time'])['GroupB_X'].apply(list)) GB_Y = np.array(Group_B.groupby(['Time'])['GroupB_Y'].apply(list)) GA = ax.scatter(GA_X[0], GA_Y[0], c = ['blue'], marker = 'o', s = 10, edgecolor = 'black') GB = ax.scatter(GB_X[0], GB_Y[0], c = ['brown'], marker = 'o', s = 10, edgecolor = 'black') return GA, GB def animate(i) : plot() groups() GA.set_offsets(np.c_[GA_X[0+i], GA_Y[0+i]]) GB.set_offsets(np.c_[GB_X[0+i], GB_Y[0+i]]) plot() groups() ani = animation.FuncAnimation(fig, animate, np.arange(0,3), interval = 1000, blit = False) Error Output:
GA = ax.scatter(GA_X[0], GA_Y[0], c = ['blue'], marker = 'o', s = 10, edgecolor = 'black') NameError: name 'ax' is not defined