How to Create Animations in Python?
Animations are a great way to make Visualizations more attractive and user appealing. It helps us to demonstrate Data Visualization in a Meaningful Way. Python helps us to create Create Animation Visualization using existing powerful Python libraries. Matplotlib is a very popular Data Visualisation Library and is used commonly used for graphical representation of data and also for animations using inbuilt functions.
There are two ways of Creating Animation using Matplotlib:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
- Using pause() function
- Using FuncAnimation() function
Method 1: Using pause() function
The pause() function in the pyplot module of the matplotlib library is used to pause for interval seconds mentioned in the argument. Consider the below example in which we will create a simple linear graph using matplotlib and show Animation in it:
- Create 2 arrays, X and Y, and store values from 1 to 100.
- Plot X and Y using plot() function.
- Add pause() function with suitable time interval
- Run the program and you’ll see the animation.
Similarly, you can use the pause() function to create Animation in various plots.
Method 2: Using FuncAnimation() function
This FuncAnimation() Function does not create the Animation on its own, but it creates Animation from series of Graphics that we pass.
Syntax: FuncAnimation(figure, animation_function, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)
Now there are Multiple types of Animation you can make using the FuncAnimation function:
Linear Graph Animation:
In this example, we are creating a simple linear graph that will show an animation of a Line. Similarly, using FuncAnimation, we can create many types of Animated Visual Representations. We just need to define our animation in a function and then pass it to FuncAnimation with suitable parameters.
Bar Plot Race Animation in Python
In this example, we are creating a simple Bar Chart animation that will show an animation of each bar.
Scatter Plot Animation in Python:
Horizontal Movement in Bar Chart Race:
- Here we will plot a Bar Chart Race using Highest Population in a city Dataset.
- Different cities will have a different bar and Bar Chart race will iterate from the year 1990 up to 2018.
- We selected countries from which the topmost cities would be picked from the dataset with the highest population.
Dataset can be download from here: city_populations