詳解在Python中創(chuàng)建條形圖追趕動(dòng)畫(huà)
前言
動(dòng)畫(huà)是使可視化更具吸引力和用戶(hù)吸引力的好方法。它幫助我們以有意義的方式展示數(shù)據(jù)可視化。Python 幫助我們使用現(xiàn)有的強(qiáng)大 Python 庫(kù)創(chuàng)建動(dòng)畫(huà)可視化。Matplotlib是一個(gè)非常流行的數(shù)據(jù)可視化庫(kù),通常用于數(shù)據(jù)的圖形表示以及使用內(nèi)置函數(shù)的動(dòng)畫(huà)。
使用 Matplotlib 創(chuàng)建動(dòng)畫(huà)有兩種方法:
- 使用 pause() 函數(shù)
- 使用 FuncAnimation() 函數(shù)
方法一:使用 pause() 函數(shù)
在暫停()的matplotlib庫(kù)的pyplot模塊在功能上用于暫停為參數(shù)提到間隔秒??紤]下面的示例,我們將使用 matplotlib 創(chuàng)建一個(gè)簡(jiǎn)單的線(xiàn)性圖并在其中顯示動(dòng)畫(huà):
創(chuàng)建 2 個(gè)數(shù)組 X 和 Y,并存儲(chǔ)從 1 到 100 的值。
使用 plot() 函數(shù)繪制 X 和 Y。
以合適的時(shí)間間隔添加 pause() 函數(shù)
運(yùn)行程序,你會(huì)看到動(dòng)畫(huà)。
Python
from matplotlib import pyplot as plt
x = []
y = []
for i in range(100):
x.append(i)
y.append(i)
# 提及 x 和 y 限制以定義其范圍
plt.xlim(0, 100)
plt.ylim(0, 100)
# 繪制圖形
plt.plot(x, y, color = 'green')
plt.pause(0.01)
plt.show()
輸出 :

同樣,你也可以使用 pause() 函數(shù)在各種繪圖中創(chuàng)建動(dòng)畫(huà)。
方法二:使用 FuncAnimation() 函數(shù)
這個(gè)FuncAnimation() 函數(shù)不會(huì)自己創(chuàng)建動(dòng)畫(huà),而是從我們傳遞的一系列圖形中創(chuàng)建動(dòng)畫(huà)。
語(yǔ)法: FuncAnimation(figure, animation_function, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True,
**kwargs)
現(xiàn)在您可以使用 FuncAnimation 函數(shù)制作多種類(lèi)型的動(dòng)畫(huà):
線(xiàn)性圖動(dòng)畫(huà)
在這個(gè)例子中,我們將創(chuàng)建一個(gè)簡(jiǎn)單的線(xiàn)性圖,它將顯示一條線(xiàn)的動(dòng)畫(huà)。同樣,使用 FuncAnimation,我們可以創(chuàng)建多種類(lèi)型的動(dòng)畫(huà)視覺(jué)表示。我們只需要在一個(gè)函數(shù)中定義我們的動(dòng)畫(huà),然后用合適的參數(shù)將它傳遞給FuncAnimation。
Python
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
x = []
y = []
figure, ax = plt.subplots()
# 設(shè)置 x 和 y 軸的限制
ax.set_xlim(0, 100)
ax.set_ylim(0, 12)
# 繪制單個(gè)圖形
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()
輸出:

Python 中的條形圖追趕動(dòng)畫(huà)
在此示例中,我們將創(chuàng)建一個(gè)簡(jiǎn)單的條形圖動(dòng)畫(huà),它將顯示每個(gè)條形的動(dòng)畫(huà)。
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("國(guó)家")
plt.ylabel("國(guó)家GDP")
plt.bar(["印度", "中國(guó)", "德國(guó)",
"美國(guó)", "加拿大", "英國(guó)"],
[y1, y2, y3, y4, y5, y6],
color = palette)
plt.title("條形圖動(dòng)畫(huà)")
animation = FuncAnimation(fig, animation_function,
interval = 50)
plt.show()
輸出:

Python 中的散點(diǎn)圖動(dòng)畫(huà):
在這個(gè)例子中,我們將使用隨機(jī)函數(shù)在 python 中動(dòng)畫(huà)散點(diǎn)圖。我們將遍歷animation_func并在迭代時(shí)繪制 x 和 y 軸的隨機(jī)值。
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()
輸出:

條形圖追趕的水平移動(dòng)
在這里,我們將使用城市數(shù)據(jù)集中的最高人口繪制條形圖競(jìng)賽。
不同的城市會(huì)有不同的條形圖,條形圖追趕將從 1990 年到 2018 年迭代。
我從人口最多的數(shù)據(jù)集中選擇了最高城市的國(guó)家。
需要用到的數(shù)據(jù)集可以從這里下載: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() / 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='-')
ax.set_axisbelow(True)
ax.text(0, 1.12, '從 1500 年到 2018 年世界上人口最多的城市',
transform=ax.transAxes, size=24, weight=600, ha='left')
ax.text(1, 0, 'by haiyong.site | 海擁',
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()
輸出:

以上就是詳解在Python中創(chuàng)建條形圖追趕動(dòng)畫(huà)的詳細(xì)內(nèi)容,更多關(guān)于Python動(dòng)畫(huà)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python中django框架通過(guò)正則搜索頁(yè)面上email地址的方法
這篇文章主要介紹了python中django框架通過(guò)正則搜索頁(yè)面上email地址的方法,涉及django框架及正則表達(dá)式的使用技巧,需要的朋友可以參考下2015-03-03
Python日志無(wú)延遲實(shí)時(shí)寫(xiě)入的示例
今天小編就為大家分享一篇Python日志無(wú)延遲實(shí)時(shí)寫(xiě)入的示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
python,pycharm的環(huán)境變量設(shè)置方式
這篇文章主要介紹了python,pycharm的環(huán)境變量設(shè)置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01
python3使用requests模塊爬取頁(yè)面內(nèi)容的實(shí)戰(zhàn)演練
本篇文章主要介紹了python3使用requests模塊爬取頁(yè)面內(nèi)容的實(shí)戰(zhàn)演練,具有一定的參考價(jià)值,有興趣的可以了解一下2017-09-09
Python網(wǎng)頁(yè)正文轉(zhuǎn)換語(yǔ)音文件的操作方法
這篇文章主要介紹了Python網(wǎng)頁(yè)正文轉(zhuǎn)換語(yǔ)音文件的操作方法,需要的朋友可以參考下2018-12-12
Python學(xué)習(xí)之a(chǎn)syncore模塊用法實(shí)例教程
這篇文章主要介紹了Python學(xué)習(xí)之a(chǎn)syncore模塊用法,主要講述了asyncore模塊的組成、原理及相關(guān)函數(shù)的用法,對(duì)于使用Python進(jìn)行網(wǎng)絡(luò)編程來(lái)說(shuō)非常實(shí)用,需要的朋友可以參考下2014-09-09
Python畫(huà)圖時(shí)如何調(diào)用本地字體
這篇文章主要為大家介紹在通過(guò)Python繪制圖畫(huà)時(shí)如何調(diào)用本地的字體,從而解決中文亂碼的問(wèn)題。感興趣的小伙伴快來(lái)跟隨小編學(xué)習(xí)學(xué)習(xí)吧2021-12-12
python使用requests?POST提交一個(gè)鍵多個(gè)值方式
這篇文章主要介紹了python使用requests?POST提交一個(gè)鍵多個(gè)值方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02

