This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

[Comment lottery] “Welcome to the discussion in the comments section. The nuggets will draw 100 nuggets in the comments section after the diggnation project. See the event article for details.”

Animation is a great way to make visualizations more engaging and user engaging. It helps us present data visualizations in a meaningful way. Python helps us create animation visualizations using existing powerful Python libraries. Matplotlib is a very popular data visualization library, typically used for graphical representation of data and animation using built-in functions.

There are two ways to create an animation using Matplotlib:

  • Use pause()
  • Use the FuncAnimation() function

🍖 Method 1: Use pause()

The Pyplot module of the Matplotlib library in pause () is functionally used to pause for the parameter mentioned interval seconds. Consider the following example, where we will use Matplotlib to create a simple linear graph and animate it:

Create 2 arrays X and Y and store values from 1 to 100. Plot X and Y using the plot() function. Add pause() at appropriate intervals to run the program and you will see an animation.

Python

from matplotlib import pyplot as plt
  
x = []
y = []
  
for i in range(100):
    x.append(i)
    y.append(i)
  
    # Refer to x and y constraints to define their scope
    plt.xlim(0.100)
    plt.ylim(0.100)
      
    # draw graph
    plt.plot(x, y, color = 'green')
    plt.pause(0.01)
  
plt.show()
Copy the code

Output:

Similarly, you can use pause() to create animations in various drawings.

🚀 Method two: use FuncAnimation()

The FuncAnimation() function does not create the animation itself, but instead creates the animation from a series of shapes we pass around.

Grammar: FuncAnimation(figure, animation_function, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)

Now you can use the FuncAnimation function to create many types of animations:

🥋 Linear graph animation:

In this example, we will create a simple linear graph that will show an animation of a line. Also, using FuncAnimation, we can create visual representations of many types of animations. All we need to do is define our animation in a function and pass it to FuncAnimation with the appropriate parameters.

Python

from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
  
x = []
y = []
  
figure, ax = plt.subplots()
  
# Set x and y limits
ax.set_xlim(0.100)
ax.set_ylim(0.12)
  
# Draw a single graph
line,  = ax.plot(0.0) 
  
def animation_function(i) :
    x.append(i * 15)
    y.append(i)
  
    line.set_xdata(x)
    line.set_ydata(y)
    return line,
  
animation = FuncAnimation(figure,
                          func = animation_function,
                          frames = np.arange(0.10.0.1), 
                          interval = 10)
plt.show()
Copy the code

Output:

🎻 Bar chart chase animation in Python

In this example, we will create a simple bar graph animation that will display an animation for each bar.

Python

from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation, writers
import numpy as np

plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  
fig = plt.figure(figsize = (7.5))
axes = fig.add_subplot(1.1.1)
axes.set_ylim(0.300)
palette = ['blue'.'red'.'green'.'darkorange'.'maroon'.'black']

y1, y2, y3, y4, y5, y6 = [], [], [], [], [], []

def animation_function(i) :
	y1 = i
	y2 = 6 * i
	y3 = 3 * i
	y4 = 2 * i
	y5 = 5 * i
	y6 = 3 * i

	plt.xlabel("Country")
	plt.ylabel("National GDP")
	
	plt.bar(["India"."China"."Germany"."The United States." "."Canada"."British"],
			[y1, y2, y3, y4, y5, y6],
			color = palette)

plt.title("Bar chart animation")

animation = FuncAnimation(fig, animation_function,
						interval = 50)
plt.show()
Copy the code

Output:

🌌 Scatter diagram animation in Python:

In this example, we will animate a scatter plot in Python using random functions. We will iterate over animation_func and draw random x and y values as we iterate.

from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
import random
import numpy as np

x = []
y = []
colors = []
fig = plt.figure(figsize=(7.5))

def animation_func(i) :
	x.append(random.randint(0.100))
	y.append(random.randint(0.100))
	colors.append(np.random.rand(1))
	area = random.randint(0.30) * random.randint(0.30)
	plt.xlim(0.100)
	plt.ylim(0.100)
	plt.scatter(x, y, c = colors, s = area, alpha = 0.5)

animation = FuncAnimation(fig, animation_func,
						interval = 100)
plt.show()
Copy the code

Output:

🛹 bar chart catching horizontal movement:

Here, we’ll have a bar chart contest using the highest population in a city’s data set. Different cities will have different bar charts and the bar chart catch-up will be iterated from 1990 to 2018. I chose the countries with the highest cities from the most populous data set. The data set to be used can be downloaded here: city_POPULATIONS

Python

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.animation import FuncAnimation
  
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  
df = pd.read_csv('city_populations.csv',
                 usecols=['name'.'group'.'year'.'value'])
  
colors = dict(zip(['India'.'Europe'.'Asia'.'Latin America'.'Middle East'.'North America'.'Africa'],
                    ['#adb0ff'.'#ffb3ff'.'#90d595'.'#e48381'.'#aafbff'.'#f7bb5f'.'#eafb50']))
  
group_lk = df.set_index('name') ['group'].to_dict()
  
def draw_barchart(year) :
    dff = df[df['year'].eq(year)].sort_values(by='value',
                                              ascending=True).tail(10)
    ax.clear()
    ax.barh(dff['name'], dff['value'],
            color=[colors[group_lk[x]] for x in dff['name']])
    dx = dff['value'].max(a) /200
      
    for i, (value, name) in enumerate(zip(dff['value'],
                                          dff['name'])):
        ax.text(value-dx, i,     name,           
                size=14, weight=600,
                ha='right', va='bottom')
        ax.text(value-dx, i-25., group_lk[name],
                size=10, color='# 444444', 
                ha='right', va='baseline')
        ax.text(value+dx, i,     f'{value:,. 0f}', 
                size=14, ha='left',  va='center')
         
    ax.text(1.0.4, year, transform=ax.transAxes, 
            color='# 777777', size=46, ha='right',
            weight=800)
    ax.text(0.1.06.'Population (thousands)',
            transform=ax.transAxes, size=12,
            color='# 777777')
      
    ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
    ax.xaxis.set_ticks_position('top')
    ax.tick_params(axis='x', colors='# 777777', labelsize=12)
    ax.set_yticks([])
    ax.margins(0.0.01)
    ax.grid(which='major', axis='x', linestyle=The '-')
    ax.set_axisbelow(True)
    ax.text(0.1.12.'World's most populous cities from 1500 to 2018',
            transform=ax.transAxes, size=24, weight=600, ha='left')
      
    ax.text(1.0.'by haiyong. On site | sea', 
            transform=ax.transAxes, ha='right', color='# 777777', 
            bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
    plt.box(False)
    plt.show()
  
fig, ax = plt.subplots(figsize=(15.8))
animator = FuncAnimation(fig, draw_barchart, 
                         frames = range(1990.2019))
plt.show()
Copy the code

Output:

🛬 wuhu! Take off!

I’ve been writing technical blogs for a long time, mostly through Nuggets, and this is one of my introductory Python projects. I like to share technology and happiness through articles. You can visit my blog at juejin.cn/user/204034… For more information. Hope you like it! 😊

💌 welcomes your comments and suggestions in the comments section! Nuggets officials will be in theProject DiggAfter the event, 100 nuggets will be selected in the comments section. For details, see the event article “💌”

If you really learn something new from this article, like it, bookmark it and share it with your friends. 🤗 and finally, don’t forget ❤ or 📑.