Data Visualizations But Animated – Python

Hey there, Python Enthusiasts! I am sure you guys have worked with Data Visualizations in Python and made tonnes of charts to make your data more visually appealing and informative through data visualization. What if I told you that it’s possible to animate the same charts to make them even more user-friendly and fun for you to learn and understand the information?

Also Read: Create a pie chart using Matplotlib in Python

Seems complex right? Well, I am here to make it simple, easy, and fun for you to learn and implement the Animated Data Visualizations in Python. So, without wasting any more time let’s get right on with learning!

Overview of Animated Data Visualizations

Animated data visualization is like bringing your information to life using moving elements in charts or graphs. They help to make your charts more engaging and informative for the users. Normally, we use graphs and charts to understand data in the form of drawings. But sometimes, data might change over time, and a static chart might not be able to cover the whole story and changes.

Importance of Animated Data Visualization

There are many benefits of using Animated Data Visualizations. I have mentioned a few below:

  1. It helps the user see how data is changing making it easier to understand complex information.
  2. It keeps the user interested because there’s movement and change happening all the time in the visualizations.
  3. It might help draw attention to some information that might get missed when using static visualizations.

Implementing Simple Animated Data Visualizations in Python

The moment we hear the term ‘data visualization’, the first and foremost library that comes to our mind is ‘Matplotlib’ and that’s the library we will be using in this tutorial as well to implement animated charts and graphs. In case you don’t have matplotlib installed in your system then use the command : pip install matplotlib to install the same.

Also Read: Matplotlib scatter plot in Python

Non-Animated Scatter Plot

When you are all set and done, let’s move on to implementing the animated plots in the further sections. First, let’s create a dataset to plot on the graph later. We will do the same with the help of the module called numpy. The code below will give some random x-axis and y-axis coordinate values to plot in the graph.

import numpy as np

xAxis = np.random.rand(20)
yAxis = np.random.rand(20)

print("X-Axis Data : " , xAxis)
print("Y-Axis Data : " , yAxis)

First of all, we will plot a simple non-animated scatter plot for the data points we just got for xAxis and yAxis on execution of the code above. Have a look at the code below where we create a simple scatter plot. I have added a few size and color elements to make the plot look more appealing.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 6))
ax.scatter(xAxis, yAxis)
ax.set_title('Non-Animated Scatter Plot', size=20)
ax.set_xlabel('X-axis Values',size=20)
ax.set_ylabel('Y-axis Values',size=20)

plt.show()

When we executed the code above we got a plot as shown below.

Scatter Plot

Animated Scatter Plot

Let’s make this plot fun and update the scatter plot frame-wise. But before we do that we need to understand that to animate the plot we will be making use of a new sub-module called FuncAnimation which comes under matplotlib animations. It comes along with the matplotlib library and doesn’t need any separate installation. I will be using jupyter notebook and Hence to make the animations visible I will be using an additional command line : %matplotlib notebook.

%matplotlib notebook
from matplotlib.animation import FuncAnimation

After this is done, we will add the code to plot the simple scatter plot we saw just now.

%matplotlib notebook
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

xAxis = np.random.rand(20)
yAxis = np.random.rand(20)
fig, ax = plt.subplots(figsize=(8, 6))
Scatter_Plot = ax.scatter(xAxis, yAxis)
ax.set_title('Non-Animated Scatter Plot', size=20)
ax.set_xlabel('X-axis Values',size=20)
ax.set_ylabel('Y-axis Values',size=20)

I have just made one single change in the code snippet above in Line Number 9 where I have stored the scatter plot in a variable called Scatter_Plot. Till this point, I hope you are all clear, but our main task is to Animate this plot. In order to do this we will have to update the values over time to create an illusion of a live dataset.

Also Read: How to Define Functions in Python?

Let’s create a Python function that will be responsible for updating the values from time to time. Have a look at the code below:

def updateValues (frame):
    
    updated_X_Values = np.random.rand(20)
    updated_Y_Values = np.random.rand(20)
    
    updated_Cordinates_Values = np.column_stack((updated_X_Values, updated_Y_Values))
                                                
    Scatter_Plot.set_offsets(updated_Cordinates_Values)
    
    return Scatter_Plot,

The code is pretty simple, I would break it down the code to make it even more simpler. The function takes an argument called frame which specifies which frame is being considered to set the updated values. Next, we set the new values for x-axis and y-axis values. We will then stack the x and y values using column_stack to connect them together to form a coordinate system.

Now we have to set the values on the scatter plot, for which we will be using set_offsets function, and pass the updated coordinate system to the function. This method is used to update the positions of the points in the scatter plot. Finally, we will return a tuple containing the scatter plot object in Line number 10.

We will be using the updateValues function inside the FuncAnimation function as shown below.

animation = FuncAnimation(fig, updateValues, frames=range(100))
plt.show()

The FuncAnimation function takes a number of arguments: First is the figure that we wish to animate, Second is the function that will be used to update the values and lastly, you remember we talked about the frame values. We will pass the frame values as a range of consecutive values up to 100.

When we execute the code the output looks somewhat like this:

Animated Scatter Plot Output

Implementing Complex Animated Data Visualizations in Python

I hope things are crystal clear up till now. But how about we go in a little deeper and try to visualize more complex visualizations? Why not learn a concept to an advanced level right?

Also Read: Matplotlib Bar Chart Tutorial in Python

Implementing Animated Bar Graph in Python

In this section, we will try to visualize a Bar Plot using a real-world example. The idea that I have chosen for this tutorial is – Visualizing the Energy Consumption by different sources of Energy over time. We will be having categories such as Solar, Wind, Hydro, and Other Sources. Let’s get started by creating a static dataset first. Have a look at the code snippet below:

import numpy as np

Energy_Sources = ['Solar', 'Wind', 'Hydro', 'Other']

CATEGORIES = np.arange(len(Energy_Sources))
VALUES = np.random.rand(len(Energy_Sources))

print("CATEGORIES : " , CATEGORIES)
print("VALUES : ", VALUES)

The output of the code comes as follows:

CATEGORIES :  [0 1 2 3]
VALUES :  [0.15089965 0.89420693 0.4422749  0.5715495 ]

I know you might be wondering why we have numerical data for categories. The reason is that our system understands the language of numbers much better than the language of words. We will override the data in the Plot later when we are plotting the Bar Graph.

Now let’s plot a simple Bar Graph using the code below:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10, 6))
Bar_Graph = ax.bar(CATEGORIES, VALUES)

ax.set_title('Energy Consumption Visualization', size=20)
ax.set_xlabel('Energy Sources', size=15)
ax.set_ylabel('Energy Consumption', size=15)

ax.set_xticks(CATEGORIES)
ax.set_xticklabels(Energy_Sources)

plt.show()

Most of the code is self-explanatory. Let me explain line numbers 9 and 10 where the labels of the categories are being set. First of all, we are using set_xticks which maps the position of the labels and bars together using the language of numbers. Then, with the help of set_xticklabels we will set the label values using the language of words.

The plot we get after executing the code is as follows:

Bar Graph in Python

Next, we will be working on the update function for the Bar Graph like we did for the Scatter Plot before.

def updateValues (frame):    
    updated_Values = np.random.rand(len(Energy_Sources))
    
    for bar, height in zip(Bar_Graph, updated_Values):
        bar.set_height(height)
        
    return Bar_Graph

In this function, we have done some changed steps to update values as the data graph is changed now. We update the heights of the values using the random.rand function. Next, we will map the new heights with the label using the zip function and set_height function. Finally, we return the updated Bar Graph for a particular frame.

Finally, we will make use of the FuncAnimation function like before. There is one new parameter called repeat in the function which makes sure that the animation stops after going through the 100 frames once. Have a look at the complete code below:

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# DATA CREATION
Energy_Sources = ['Solar', 'Wind', 'Hydro', 'Other']
CATEGORIES = np.arange(len(Energy_Sources))
VALUES = np.random.rand(len(Energy_Sources))

# SIMPLE BAR GRAPH 
fig, ax = plt.subplots(figsize=(10, 6))
Bar_Graph = ax.bar(CATEGORIES, VALUES)
ax.set_title('Energy Consumption Visualization', size=20)
ax.set_xlabel('Energy Sources', size=15)
ax.set_ylabel('Energy Consumption', size=15)
ax.set_xticks(CATEGORIES)
ax.set_xticklabels(Energy_Sources)

# UPDATE VALUE FUNCTION
def updateValues (frame):    
    updated_Values = np.random.rand(len(Energy_Sources))
    for bar, height in zip(Bar_Graph, updated_Values):
        bar.set_height(height)
    return Bar_Graph

# ANIMATED GRAPH
animation = FuncAnimation(fig, updateValues, frames=range(100),repeat=False)
plt.show()

The output of the code execution is as follows:

Animated Bar Graph in Python

Implementing Animated Line Plot in Python

When we are at it, let’s also implement the animated line plot as well the same way. I hope at this point you are able to understand the code well. Here’s your challenge:

Also Read: Line Chart Plotting in Python using Matplotlib

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# DATA CREATION
Energy_Sources = ['Solar', 'Wind', 'Hydro', 'Other']
CATEGORIES = np.arange(len(Energy_Sources))
VALUES = np.random.rand(len(Energy_Sources))

# SIMPLE LINE CHART 
fig, ax = plt.subplots(figsize=(10, 6))
Line_Chart, = ax.plot(CATEGORIES, VALUES, marker='o', linestyle='-', color='b')
ax.set_title('Energy Consumption Visualization', size=20)
ax.set_xlabel('Energy Sources', size=15)
ax.set_ylabel('Energy Consumption', size=15)
ax.set_xticks(CATEGORIES)
ax.set_xticklabels(Energy_Sources)

# UPDATE VALUE FUNCTION
def updateValues(frame):    
    updated_Values = np.random.rand(len(Energy_Sources))
    Line_Chart.set_ydata(updated_Values)
    return Line_Chart,

# ANIMATED GRAPH
animation = FuncAnimation(fig, updateValues, frames=range(100),repeat=False)
plt.show()

The output of the code is as follows:

Animated Line Plot in Python

Conclusion

And there you have it! I hope you had fun learning how fun and interactive animated data visualizations look like. We visualized both Simple as well as Complex Data Visualizations and you are good to go when it comes to implementing Data Visualizations in Python.

Keep exploring and with different datasets as well or maybe colors?

Also Read :

  1. How to show a GIF animation image in Tkinter – Python
  2. How to plot points in matplotlib with Python
  3. Set or Change the Size of a Figure in Matplotlib with Python

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *