Table of Contents
We can draw several static charts first, and then draw these Just combine several charts into one animation in the format of It's very simple. We want to filter the data based on the year, and then draw a chart based on the filtered data. The charts are different for each year" >We can draw several static charts first, and then draw these Just combine several charts into one animation in the format of It's very simple. We want to filter the data based on the year, and then draw a chart based on the filtered data. The charts are different for each year
" >output
将若干张​gif动图放置在一张大图当中" >将若干张gif动图放置在一张大图当中
Home Backend Development Python Tutorial Use Python to draw cool gif animations that amaze everyone

Use Python to draw cool gif animations that amaze everyone

May 04, 2023 pm 04:19 PM
python gif animation

Use Python to draw cool gif animations that amaze everyone

In a previous article, the editor shared how to use ​​gif​## in Python​​​ #​​Module to make​​gif​​format charts, is awesome, use Python to draw dynamic visualization charts, and save them in gif format. Today I will introduce it to you. A new method of making ​

​gif​

​​ format charts, calling the relevant modules of ​​matplotlib​​, the steps and methods are also quite simple and easy to understand. .

Download and import database

The data set we used this time is the data set that comes with the ​

​bokeh​

​module, through The following line of code can directly download <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>import bokeh bokeh.sampledata.download() </pre><div class="contentsignin">Copy after login</div></div> and then import the data set to be used later. We selected the data on the proportion of the population of different age groups in the specified country from 1950 to the present

from bokeh.sampledata.population import data
import numpy as np

data = filter_loc('United States of America')
data.head()


Copy after login

output

Use Python to draw cool gif animations that amaze everyone##First draw several static charts

We can draw several static charts first, and then draw these Just combine several charts into one animation in the format of It's very simple. We want to filter the data based on the year, and then draw a chart based on the filtered data. The charts are different for each year

import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patheffects as fx

# 绘制图表的函数
def make_plot(year):
    
    # 根据年份来筛选出数据
    df = data[data.Year == year]
        
    # 制作图表
    fig, (ax1, ax2) = plt.subplots(1, 2, sharey = True)
    ax1.invert_xaxis()
    fig.subplots_adjust(wspace = 0) 
    
    ax1.barh(df[df.Sex == 'Male'].AgeGrp, df[df.Sex == 'Male'].percent, label = 'Male')
    ax2.barh(df[df.Sex == 'Female'].AgeGrp, df[df.Sex == 'Female'].percent, label = 'Female', color = 'C1')
    
    country = df.Location.iloc[0]
    if country == 'United States of America': country == 'US'
        
    fig.suptitle(f'......')
    fig.supxlabel('......')
    fig.legend(bbox_to_anchor = (0.9, 0.88), loc = 'upper right')
    ax1.set_ylabel('Age Groups')
    
    return fig


Copy after login

output

In this way, we generated several static charts, and then assembled them into several charts in ​

​gif​

​format. The code is as follows

years = [i for i in set(data.Year) if i < 2022]
years.sort()

for year in years:
    fig = make_plot(year)
    fig.savefig(f'{year}.jpeg',bbox_inches = 'tight')


Copy after login
Use Python to draw cool gif animations that amaze everyoneoutput

There is another way of thinking

Use Python to draw cool gif animations that amaze everyoneUse Python to draw cool gif animations that amaze everyoneMaybe after seeing this, some people will find the method mentioned above a little troublesome. After all, we Dozens of static charts need to be generated first. If the computer disk space is a little tight, or there is no such place to store these dozens of charts. So you will wonder if it can be done in one step. Of course it is possible. For example, if we plan to draw the distribution of population proportions at different ages from 1950 to 2020, the first step is to draw the distribution of population proportions at different ages in 1950, which is the starting year. Chart, the code is as follows

import matplotlib.animation as animation
fig, ax = plt.subplots()
ims = []

for year in years:
    im = ax.imshow(plt.imread(f'{year}.jpeg'), animated = True)
    ims.append([im])

ani = animation.ArtistAnimation(fig, ims, interval=600)
ani.save('us_population.gif')


Copy after login

output

Then we customize a function to draw the chart, where the parameter is the year, the purpose is to filter out the phase by year Corresponding data and draw corresponding charts

def run(year):
    # 通过年份来筛选出数据
    df = data[data.Year == year]
    # 针对不同地性别来绘制
    total_pop = df.Value.sum()
    df['percent'] = df.Value / total_pop * 100
    male.remove()
    y_pos = [i for i in range(len(df[df.Sex == 'Male']))]
    male.patches = ax1.barh(y_pos, df[df.Sex == 'Male'].percent, label = 'Male', 
                     color = 'C0', tick_label = df[df.Sex == 'Male'].AgeGrp)
    female.remove()
    female.patches = ax2.barh(y_pos, df[df.Sex == 'Female'].percent, label = 'Female',
                 
                 color = 'C1', tick_label = df[df.Sex == 'Female'].AgeGrp)

    text.set_text(year)
    return male#, female


Copy after login

然后我们调用​​animation.FuncAnimation()​​方法,

ani = animation.FuncAnimation(fig, run, years, blit = True, repeat = True, 
                              interval = 600)
ani.save('文件名.gif')


Copy after login

output

Use Python to draw cool gif animations that amaze everyone

这样就可以一步到位生成​​gif​​格式的图表,避免生成数十张繁多地静态图片了。

将若干张​<span style="color: #2b2b2b;">gif</span>​动图放置在一张大图当中

最后我们可以将若干张​​gif​​动图放置在一张大的图表当中,代码如下

import matplotlib.animation as animation

# 创建一个新的画布
fig, (ax, ax2, ax3) = plt.subplots(1, 3, figsize = (10, 3))

ims = []
for year in years:
    im = ax.imshow(plt.imread(f'文件1{year}.jpeg'), animated = True)
    im2 = ax2.imshow(plt.imread(f'文件2{year}.jpeg'), animated = True)
    im3 = ax3.imshow(plt.imread(f'文件3{year}.jpeg'), animated = True)
    ims.append([im, im2, im3])

ani = animation.ArtistAnimation(fig, ims, interval=600)
ani.save('comparison.gif')


Copy after login

output

Use Python to draw cool gif animations that amaze everyone


The above is the detailed content of Use Python to draw cool gif animations that amaze everyone. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Apr 01, 2025 pm 05:24 PM

Choice of Python Cross-platform desktop application development library Many Python developers want to develop desktop applications that can run on both Windows and Linux systems...

Do Google and AWS provide public PyPI image sources? Do Google and AWS provide public PyPI image sources? Apr 01, 2025 pm 05:15 PM

Many developers rely on PyPI (PythonPackageIndex)...

How to efficiently count and sort large product data sets in Python? How to efficiently count and sort large product data sets in Python? Apr 01, 2025 pm 08:03 PM

Data Conversion and Statistics: Efficient Processing of Large Data Sets This article will introduce in detail how to convert a data list containing product information to another containing...

How to optimize processing of high-resolution images in Python to find precise white circular areas? How to optimize processing of high-resolution images in Python to find precise white circular areas? Apr 01, 2025 pm 06:12 PM

How to handle high resolution images in Python to find white areas? Processing a high-resolution picture of 9000x7000 pixels, how to accurately find two of the picture...

How to solve the problem of file name encoding when connecting to FTP server in Python? How to solve the problem of file name encoding when connecting to FTP server in Python? Apr 01, 2025 pm 06:21 PM

When using Python to connect to an FTP server, you may encounter encoding problems when obtaining files in the specified directory and downloading them, especially text on the FTP server...

See all articles