Animating Bar Plots

I’m trying to animate a bar plot. Consider the following bit of code (which works fine):

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation, rc

def animate(i):
    xx = np.linspace(0, 5, 2+i)
    yy = xx**2
    line.set_data(xx, yy)
    ax.set_title("Frame = {:d}".format(i))
    return (line,)


fig, ax = plt.subplots()
ax.set_xlim(0,5)
ax.set_ylim(0,25)

line, = ax.plot([], [], "ro-")

anim = animation.FuncAnimation(fig, animate,
                               frames=10, interval=500, blit=True)

This animates a section of a parabola as more and more points are added to it. I would like to do the analog with a bar plot, where both the number of bars and their heights change with each frame. But I haven’t seen an example handling this, and I’m not sure where to begin.

Hello and welcome !!!

Try this (a very blunt approach) :

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

def animate(i):
  plt.clf()
  xx = np.linspace(0, 5, 2+i)
  yy = xx**2
  plt.bar(xx, yy)
  plt.title("Frame = {:d}".format(i))

  return ()


fig, ax = plt.subplots()

anim = animation.FuncAnimation(fig, animate,
                           frames=10, interval=500, blit=True)
1 Like