Why does my matplotlib animation give an empty axis?

Viewed 39

I am trying to animate a simple demonstration of Benfold's Law. I am expecting an animated bar graph from this code:

import matplotlib.animation as animation

fig = plt.figure()
plt.xticks(np.arange(1,10))

def animate(i):
    plt.title("Iteration: " + str(i))
    plt.plot(np.arange(1,10,1),1000*benford[1:], linestyle="", marker="d",color='r')
    plt.bar(all_leads[i].keys(), all_leads[i].values())
   

ani = animation.FuncAnimation(fig, animate, interval=100)
plt.show()

I get an empty plot.

Empty Plot

The animate(i) function works to give a correct individual plot

animate(10)

Image of correctly produced plot

Any ideas what I am doing wrong.

1 Answers

Because I don't have your data, I made a mock animation as best I could from what was provided. First, you have to plot your graph outside of the animate function, then you have to update the x and y data within the animate function, lastly - to loop your animation, you have to set frames to some value (we will go with 10 for your case). While this all isn't perfectly in line with your graphs (again, I don't have your data), this should get you started. You can also take a look at my other answer for an additional example.

%matplotlib notebook # If you are working in jupyter notebook
import matplotlib.animation as animation

fig,ax = plt.subplots()
plt.xticks(np.arange(1,10))
plot, = ax.plot(np.arange(1,10,1),np.arange(1,10,1), linestyle="", marker="d",color='r')

def animate(i):
    plot.set_ydata(np.arange(1,10,1)[i:i+3])
    plot.set_xdata(np.arange(1,10,1)[i:i+3])
    plt.title("Iteration: " + str(i))       

ani = animation.FuncAnimation(fig, animate, interval=100, frames=10)
plt.show()

enter image description here

You can also add an xlim argument in the animate function to follow your animation across the x-axis:

def animate(i):
    plot.set_ydata(np.arange(1,10,1)[i:i+3])
    plot.set_xdata(np.arange(1,10,1)[i:i+3])
    plt.title("Iteration: " + str(i))    
    plt.xlim(i, i+4)

Gives:

enter image description here

Related