Dynamically updating a bar plot in Matplotlib


To update a bar plot dynamically in Matplotlib, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.
  • Create a new figure or activate an existing figure.
  • Make a list of data points and colors.
  • Plot the bars with data and colors, using bar() method.
  • Using FuncAnimation() class, make an animation by repeatedly calling a function, animation, that sets the height of the bar and facecolor of the bars.
  • To display the figure, use show() method.

Example

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

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()

data = [1, 4, 3, 2, 6, 7, 3]
colors = ['red', 'yellow', 'blue', 'green', 'black']
bars = plt.bar(data, data, facecolor='green', alpha=0.75)

def animate(frame):
   global bars
   index = np.random.randint(1, 7)
   bars[frame].set_height(index)
   bars[frame].set_facecolor(colors[np.random.randint(0, len(colors))])

ani = animation.FuncAnimation(fig, animate, frames=len(data))

plt.show()

Output

Updated on: 08-Jul-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements