Matplotlib is a well-known python library used for data visualisation, we usually create static plots with it. But how if we create animated graph to present the evolution in terms of time? In this...
Matplotlib is a well-known python library used for data visualisation, we
usually create static plots with it. But how if we create animated graph to
present the evolution in terms of time? In this blog, I will show you how to
create animated graphs with matplotlib in the following point:
Libraries
Data preparation
Animated graph with static legend
Animated graph with animated legend
Libraries
Data preparation
Here I use a dataset which contains the daily cumulative confirmed COVID-19
cases of each country, for the animated graph, I’ll use the top 6 countries.
Animated graph with static legend
Firstly, I will create a figure with necessary parameters:
We need to create a function animate() to create the animate plot frame by
frame, then apply it with matplotlib.animation.FuncAnimation().
I set frames=51 since we have data on 51 different days; interval means the
delay between frames in milliseconds; if the animation in repeated, adds a
repeat_delay in milliseconds before repeating the animation. Thus, the result
should like:
Animated graph with animated legend
In the animated graph above, the legend for each line is fixed at the corner,
it’s not convenient to distinct the country when we focus on the changes of each
line. Why not animate the legends and let them move with lines? It’s similar as
the steps for the graph above, but we need to add the text into the graph with
annotate().
I firstly set the text with annotate() when I created the figure, then in the
function animate() I updated the annotation position and text with
.set_position(), .xy and .set_text(). Thus, the result is like:
If you are interested in the scripts, please find them here.