詳解在Python中創(chuàng)建條形圖追趕動(dòng)畫
前言
動(dòng)畫是使可視化更具吸引力和用戶吸引力的好方法。它幫助我們以有意義的方式展示數(shù)據(jù)可視化。Python 幫助我們使用現(xiàn)有的強(qiáng)大 Python 庫(kù)創(chuàng)建動(dòng)畫可視化。Matplotlib是一個(gè)非常流行的數(shù)據(jù)可視化庫(kù),通常用于數(shù)據(jù)的圖形表示以及使用內(nèi)置函數(shù)的動(dòng)畫。
使用 Matplotlib 創(chuàng)建動(dòng)畫有兩種方法:
- 使用 pause() 函數(shù)
- 使用 FuncAnimation() 函數(shù)
方法一:使用 pause() 函數(shù)
在暫停()的matplotlib庫(kù)的pyplot模塊在功能上用于暫停為參數(shù)提到間隔秒??紤]下面的示例,我們將使用 matplotlib 創(chuàng)建一個(gè)簡(jiǎn)單的線性圖并在其中顯示動(dòng)畫:
創(chuàng)建 2 個(gè)數(shù)組 X 和 Y,并存儲(chǔ)從 1 到 100 的值。
使用 plot() 函數(shù)繪制 X 和 Y。
以合適的時(shí)間間隔添加 pause() 函數(shù)
運(yùn)行程序,你會(huì)看到動(dòng)畫。
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)畫。
方法二:使用 FuncAnimation() 函數(shù)
這個(gè)FuncAnimation() 函數(shù)不會(huì)自己創(chuàng)建動(dòng)畫,而是從我們傳遞的一系列圖形中創(chuàng)建動(dòng)畫。
語(yǔ)法: FuncAnimation(figure, animation_function, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True,
**kwargs)
現(xiàn)在您可以使用 FuncAnimation 函數(shù)制作多種類型的動(dòng)畫:
線性圖動(dòng)畫
在這個(gè)例子中,我們將創(chuàng)建一個(gè)簡(jiǎn)單的線性圖,它將顯示一條線的動(dòng)畫。同樣,使用 FuncAnimation,我們可以創(chuàng)建多種類型的動(dòng)畫視覺表示。我們只需要在一個(gè)函數(shù)中定義我們的動(dòng)畫,然后用合適的參數(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)畫
在此示例中,我們將創(chuàng)建一個(gè)簡(jiǎn)單的條形圖動(dòng)畫,它將顯示每個(gè)條形的動(dòng)畫。
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)畫") animation = FuncAnimation(fig, animation_function, interval = 50) plt.show()
輸出:
Python 中的散點(diǎn)圖動(dòng)畫:
在這個(gè)例子中,我們將使用隨機(jī)函數(shù)在 python 中動(dòng)畫散點(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)畫的詳細(xì)內(nèi)容,更多關(guān)于Python動(dòng)畫的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python使用execjs執(zhí)行包含中文參數(shù)的JavaScript
爬蟲的開發(fā)過程中,往往需要對(duì)JS進(jìn)行模擬,簡(jiǎn)單或者通用的還可以在Python中模擬或者找到對(duì)應(yīng)的第三方庫(kù),但是復(fù)雜的就可能不好實(shí)現(xiàn)了,下面這篇文章主要給大家介紹了關(guān)于Python使用execjs執(zhí)行包含中文參數(shù)的JavaScript的相關(guān)資料,需要的朋友可以參考下2022-03-03python實(shí)現(xiàn)密度聚類(模板代碼+sklearn代碼)
這篇文章主要介紹了python實(shí)現(xiàn)密度聚類(模板代碼+sklearn代碼),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04Flask框架運(yùn)用Ajax實(shí)現(xiàn)數(shù)據(jù)交互的示例代碼
使用Ajax技術(shù)網(wǎng)頁(yè)應(yīng)用能夠快速地將增量更新呈現(xiàn)在用戶界面上,而不需要重載刷新整個(gè)頁(yè)面,這使得程序能夠更快地回應(yīng)用戶的操作,本文將簡(jiǎn)單介紹使用AJAX如何實(shí)現(xiàn)前后端數(shù)據(jù)通信2022-11-11keras中epoch,batch,loss,val_loss用法說明
這篇文章主要介紹了keras中epoch,batch,loss,val_loss用法說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07keras 獲取某層輸出 獲取復(fù)用層的多次輸出實(shí)例
這篇文章主要介紹了keras 獲取某層輸出 獲取復(fù)用層的多次輸出實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python如何使用Gitlab API實(shí)現(xiàn)批量的合并分支
這篇文章主要介紹了Python如何使用Gitlab API實(shí)現(xiàn)批量的合并分支,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11python numpy.ndarray中如何將數(shù)據(jù)轉(zhuǎn)為int型
這篇文章主要介紹了python numpy.ndarray中如何將數(shù)據(jù)轉(zhuǎn)為int型,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05剖析Python的Tornado框架中session支持的實(shí)現(xiàn)代碼
這篇文章主要介紹了剖析Python的Tornado框架中session支持的實(shí)現(xiàn)代碼,這樣就可以使用Django等框架中大家所熟悉的session了,需要的朋友可以參考下2015-08-08詳解Pytorch如何利用yaml定義卷積網(wǎng)絡(luò)
大多數(shù)卷積神經(jīng)網(wǎng)絡(luò)都是直接通過寫一個(gè)Model類來定義的,這樣寫的代碼其實(shí)是比較好懂,也很方便。但是本文將介紹另一個(gè)方法:利用yaml定義卷積網(wǎng)絡(luò),感興趣的可以了解一下2022-10-10淺析Python 簡(jiǎn)單工廠模式和工廠方法模式的優(yōu)缺點(diǎn)
這篇文章主要介紹了Python 工廠模式的相關(guān)資料,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07