Pages

How to create a line animation in Python?

 A simple application without images or any animation looks boring. It won't be able to keep people interested for more than 5 minutes, but interactive animations can make any app more appealing to people who might buy it. So, in today's blog, we will learn the basics of creating animation in Python, how it works, and how we can create a line and bar chart animation in Python.


How do animations work in Python?

Python animations are made by making a series of visual states and then showing them one after the other quickly enough that the changes don't seem abrupt to the human eye. This is achieved using the animation module of the Matplotlib library in Python.


The animation module lets you make animations by calling a function over and over again to change the state of the plot's visual elements. This function is called for each frame of the animation and is responsible for updating the state of the plot. The animation is then shown using the animation module's FuncAnimation class, which takes as an argument the update function and makes the animation frames.


The FuncAnimation class also has a number of parameters that can be used to control the speed and timing of the animation. These parameters include the number of frames per second (fps), the time between frames, and the total number of frames to be shown.


By changing the plot in each frame and showing the frames quickly one after the other, we can make it look like the plot is moving. This is how animations work in Python using the Matplotlib library.


Basics of creating animation in Python:

We will utilize the matplotlib animation routines to generate animations in Python. Using Matplotlib, we can easily create animations. Before creating an animation, it is necessary to understand what to make and what each term means.


Fig: This is the parameter for the function figure() in the matplotlib library. The user can paint the image on the surface using this parameter. 


Func: func is an argument in the matplotlib library given to the function identity_decorator(). The expression func() means "call the function assigned to the variable func." The decorator is taking another function as an argument and returns a new function (defined as "wrapper) that executes the given function "func" when it is run.


interval: is the amount of time, measured in milliseconds, between each animation frame.


Frames: A frame is the number of images or conditions that we want to show in our animation. Let's understand it with an example. If we have to show the data of 2 different countries in our animation, the frame will 2, and if we want to show the data of 50 different places, the frames will increase by 50. 


These are the four major arguments that people usually use in Python programming. We can create any type of animation or chart using these four arguments.

As we have already gathered thorough knowledge of arguments used in the Matplotlib library now it's time to create designing the desired graphic before starting the animation designing part.


Creating a line animation in Python:

To create a line animation in python first we have to import libraries and prepare data to show on the chart through lines. Roughly designing the graph will help you to get a better idea of what to use where. 


Assume we're making a line chart animation of GDP vs. capita for three countries: Italy, Spain, and the United States. Here is how our graphical form of animation will look. 



Now that we have our graph ready, it's time to move ahead and create a line animation for the graph. To make the graph, we will first write a function for each iteration that will generate the line graph for the available data. 


from matplotlib import animation


countries_plot = ['Spain', 'Italy', 'United States']

linechart_plot = gapminder.loc[gapminder['country'].isin(countries_plot), :]


# Define colors

colors = ['red', 'green', 'blue']


fig, ax = plt.subplots()


def update_linechart(i):

  for j in range(len(colors)):

    country = countries_plot[j]

    color = colors[j]


    data = linechart_plot.loc[linechart_plot['country'] == country,:]

    ax.plot(data.year[:i], data.gdpPercap[:i], color)


In the above codes, the line graph should create one point for the year 1952 in the first iteration, and the second point for the year 1957 in the second iteration. We can add as many points as we want to the graph until it is complete.


Since we only need to use the indices to specify the data that the graph must capture, creating this iteration after creating the graph is fortunately quite easy.


In the above code, we have created everything that we need in our graph for animation. Now Its time to use the FuncAnimation function.


num_frames = len(linechart_plot['year'].unique())        

anim = animation.FuncAnimation(fig, update_linechart, frames = num_frames)

anim.save('linechart.gif')


That is how our line chart would look like.


Creating a bar chart animation in Python:

In the above section of this blog, we learned to create the simplest animation in Python, which is a line chart. Now it's time to expand our knowledge and learn something new. So, now we will learn to create a bar chart. 


Creating a bar chart with Python is much easier now because we already know the basics of creating animation in Python. A bar chart makes it much easier to understand the statistics and compare them than a line animation. 


To get started, we will draw a graph that we want to achieve from our data. So, this time, we'll compare GDP vs. per capita income in various countries.


countries_plot = ['Spain', 'Italy', 'United States','Ireland','China']

barchart_data  = gapminder.loc[gapminder['country'].isin(countries_plot), :]


font = {

    'weight': 'normal',

    'size'  :  40,

    'color': 'lightgray'

}


colors =['#FF0000','#169b62','#008c45','#aa151b','#002868']


data_temp = barchart_data.loc[barchart_data['year'] == 2007, :]


fig, ax = plt.subplots(figsize=(10, 5))

ax.clear()

ax.barh(data_temp.country,data_temp.gdpPercap, color = colors)


ax.text(0.95, 0.2, data_temp['year'].iloc[0],

        horizontalalignment='right',

        verticalalignment='top',

        transform=ax.transAxes,

       fontdict=font)

plt.show()




In the above codes, we have made two major changes. Let’s see how they are going to affect our bar chart.


  1. Cleaning the old graph

If we create the graph inside of our ax object, the graphs will "crowd" us, which may cause our data to not be an accurate representation of the situation. To make matters worse, if you do not use transparency on the chart, you might not even be aware of this fact depending on the type of chart you are using.


In order to avoid this, we need to make sure that at each iteration we call the ax.clear() function in such a way that it clears the result from the previous frame.


  1. Filter the data in the update function

The process of creating an animation for a single year is not overly complicated, as any novice developer can do it easily by making a few changes to the code. However, if you want to show the data for multiple years on your bar chart, then it is somewhat more difficult than creating the bar chart for a single year. Only for this reason, we use animation in Python. In Python, anyone can easily create bar chart animations for multiple attributes. 


To perform this, we have to do the following tasks.


  • Make a list of all the states, countries, or whatever attribute you want to add in the bar chart. 

  • Performs a filtering operation on the entire dataset based on the current state of the update function.

Animated GIFs will be significantly simpler for you to create once you have completed these two steps.


Now we will develop the update function for our barplot animation considering the above mentioned points.


countries_plot = ['Spain', 'Italy', 'United States','Ireland','China']

barchart_data  = gapminder.loc[gapminder['country'].isin(countries_plot), :]


font = {

    'weight': 'normal',

    'size'  :  40,

    'color': 'lightgray'

}


years = barchart_data['year'].unique()

colors =['#FF0000','#169b62','#008c45','#aa151b','#002868']


fig, ax = plt.subplots(figsize=(10, 5))

label = ax.text(0.95, 0.2, years[0],

            horizontalalignment='right',

            verticalalignment='top',

            transform=ax.transAxes,

            fontdict=font)


def update_barchart(i):

  year = years[i]


  data_temp = barchart_data.loc[barchart_data['year'] == year, :]

  ax.clear()

  ax.barh(data_temp.country,data_temp.gdpPercap, color = colors)

  label.set_text(year)


anim = animation.FuncAnimation(fig, update_barchart, frames = len(years))

anim.save('barchart.gif')  




This image shows our final barplot animation! In this bar chart, the data is simpler to understand than in the line animation. Also, bar charts provide us with more control over the animations than simpler line animations. 


Final thoughts: 

In this article, we have learned so much about animation in Python. We have learned how animations exactly work in Python and how to create line animation and bar chart animation in Python. Many other types of animations are still pending to be learned, like barplot race animations and scatter plots, which we will explain in our next blog. I hope you all have understood the basic concept of designing animations in Python. It will help readers understand the data in a better manner. 


No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...