溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

在Python中怎么創(chuàng)建條形圖追趕動(dòng)畫

發(fā)布時(shí)間:2022-03-11 11:46:35 來(lái)源:億速云 閱讀:118 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“在Python中怎么創(chuàng)建條形圖追趕動(dòng)畫”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

前言

動(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()

輸出 :

在Python中怎么創(chuàng)建條形圖追趕動(dòng)畫

同樣,你也可以使用 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中怎么創(chuàng)建條形圖追趕動(dòng)畫

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中怎么創(chuàng)建條形圖追趕動(dòng)畫

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()

輸出:

在Python中怎么創(chuàng)建條形圖追趕動(dòng)畫

條形圖追趕的水平移動(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)畫

“在Python中怎么創(chuàng)建條形圖追趕動(dòng)畫”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI