- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements