亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

詳解在Python中創(chuàng)建條形圖追趕動畫

 更新時間:2022年03月11日 10:34:36   作者:海擁?  
動畫是使可視化更具吸引力和用戶吸引力的好方法。它幫助我們以有意義的方式展示數(shù)據(jù)可視化。Matplotlib是一個非常流行的數(shù)據(jù)可視化庫,通常用于數(shù)據(jù)的圖形表示以及使用內(nèi)置函數(shù)的動畫。本文將用Matplotlib繪制條形圖追趕動畫,需要的可以參考一下

前言

動畫是使可視化更具吸引力和用戶吸引力的好方法。它幫助我們以有意義的方式展示數(shù)據(jù)可視化。Python 幫助我們使用現(xiàn)有的強(qiáng)大 Python 庫創(chuàng)建動畫可視化。Matplotlib是一個非常流行的數(shù)據(jù)可視化庫,通常用于數(shù)據(jù)的圖形表示以及使用內(nèi)置函數(shù)的動畫。

使用 Matplotlib 創(chuàng)建動畫有兩種方法:

  • 使用 pause() 函數(shù)
  • 使用 FuncAnimation() 函數(shù)

方法一:使用 pause() 函數(shù)

在暫停()的matplotlib庫的pyplot模塊在功能上用于暫停為參數(shù)提到間隔秒。考慮下面的示例,我們將使用 matplotlib 創(chuàng)建一個簡單的線性圖并在其中顯示動畫:

創(chuàng)建 2 個數(shù)組 X 和 Y,并存儲從 1 到 100 的值。

使用 plot() 函數(shù)繪制 X 和 Y。

以合適的時間間隔添加 pause() 函數(shù)

運(yùn)行程序,你會看到動畫。

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)建動畫。

方法二:使用 FuncAnimation() 函數(shù)

這個FuncAnimation() 函數(shù)不會自己創(chuàng)建動畫,而是從我們傳遞的一系列圖形中創(chuàng)建動畫。

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

現(xiàn)在您可以使用 FuncAnimation 函數(shù)制作多種類型的動畫:

線性圖動畫

在這個例子中,我們將創(chuàng)建一個簡單的線性圖,它將顯示一條線的動畫。同樣,使用 FuncAnimation,我們可以創(chuàng)建多種類型的動畫視覺表示。我們只需要在一個函數(shù)中定義我們的動畫,然后用合適的參數(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)
  
# 繪制單個圖形
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 中的條形圖追趕動畫

在此示例中,我們將創(chuà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("國家")
	plt.ylabel("國家GDP")
	
	plt.bar(["印度", "中國", "德國",
			"美國", "加拿大", "英國"],
			[y1, y2, y3, y4, y5, y6],
			color = palette)

plt.title("條形圖動畫")

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

輸出:

Python 中的散點圖動畫:

在這個例子中,我們將使用隨機(jī)函數(shù)在 python 中動畫散點圖。我們將遍歷animation_func并在迭代時繪制 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()

輸出:

條形圖追趕的水平移動

在這里,我們將使用城市數(shù)據(jù)集中的最高人口繪制條形圖競賽。

不同的城市會有不同的條形圖,條形圖追趕將從 1990 年到 2018 年迭代。

我從人口最多的數(shù)據(jù)集中選擇了最高城市的國家。

需要用到的數(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)建條形圖追趕動畫的詳細(xì)內(nèi)容,更多關(guān)于Python動畫的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python使用execjs執(zhí)行包含中文參數(shù)的JavaScript

    Python使用execjs執(zhí)行包含中文參數(shù)的JavaScript

    爬蟲的開發(fā)過程中,往往需要對JS進(jìn)行模擬,簡單或者通用的還可以在Python中模擬或者找到對應(yīng)的第三方庫,但是復(fù)雜的就可能不好實現(xiàn)了,下面這篇文章主要給大家介紹了關(guān)于Python使用execjs執(zhí)行包含中文參數(shù)的JavaScript的相關(guān)資料,需要的朋友可以參考下
    2022-03-03
  • python實現(xiàn)密度聚類(模板代碼+sklearn代碼)

    python實現(xiàn)密度聚類(模板代碼+sklearn代碼)

    這篇文章主要介紹了python實現(xiàn)密度聚類(模板代碼+sklearn代碼),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • Flask框架運(yùn)用Ajax實現(xiàn)數(shù)據(jù)交互的示例代碼

    Flask框架運(yùn)用Ajax實現(xiàn)數(shù)據(jù)交互的示例代碼

    使用Ajax技術(shù)網(wǎng)頁應(yīng)用能夠快速地將增量更新呈現(xiàn)在用戶界面上,而不需要重載刷新整個頁面,這使得程序能夠更快地回應(yīng)用戶的操作,本文將簡單介紹使用AJAX如何實現(xiàn)前后端數(shù)據(jù)通信
    2022-11-11
  • keras中epoch,batch,loss,val_loss用法說明

    keras中epoch,batch,loss,val_loss用法說明

    這篇文章主要介紹了keras中epoch,batch,loss,val_loss用法說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • keras 獲取某層輸出 獲取復(fù)用層的多次輸出實例

    keras 獲取某層輸出 獲取復(fù)用層的多次輸出實例

    這篇文章主要介紹了keras 獲取某層輸出 獲取復(fù)用層的多次輸出實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • Python如何使用Gitlab API實現(xiàn)批量的合并分支

    Python如何使用Gitlab API實現(xiàn)批量的合并分支

    這篇文章主要介紹了Python如何使用Gitlab API實現(xiàn)批量的合并分支,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-11-11
  • python numpy.ndarray中如何將數(shù)據(jù)轉(zhuǎn)為int型

    python numpy.ndarray中如何將數(shù)據(jù)轉(zhuǎn)為int型

    這篇文章主要介紹了python numpy.ndarray中如何將數(shù)據(jù)轉(zhuǎn)為int型,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • 剖析Python的Tornado框架中session支持的實現(xiàn)代碼

    剖析Python的Tornado框架中session支持的實現(xiàn)代碼

    這篇文章主要介紹了剖析Python的Tornado框架中session支持的實現(xiàn)代碼,這樣就可以使用Django等框架中大家所熟悉的session了,需要的朋友可以參考下
    2015-08-08
  • 詳解Pytorch如何利用yaml定義卷積網(wǎng)絡(luò)

    詳解Pytorch如何利用yaml定義卷積網(wǎng)絡(luò)

    大多數(shù)卷積神經(jīng)網(wǎng)絡(luò)都是直接通過寫一個Model類來定義的,這樣寫的代碼其實是比較好懂,也很方便。但是本文將介紹另一個方法:利用yaml定義卷積網(wǎng)絡(luò),感興趣的可以了解一下
    2022-10-10
  • 淺析Python 簡單工廠模式和工廠方法模式的優(yōu)缺點

    淺析Python 簡單工廠模式和工廠方法模式的優(yōu)缺點

    這篇文章主要介紹了Python 工廠模式的相關(guān)資料,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07

最新評論