欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

如何使用Python創(chuàng)建條形圖追趕動(dòng)畫(huà)-創(chuàng)新互聯(lián)

這篇文章主要介紹了如何使用Python創(chuàng)建條形圖追趕動(dòng)畫(huà),具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

壺關(guān)網(wǎng)站制作公司哪家好,找成都創(chuàng)新互聯(lián)公司!從網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、APP開(kāi)發(fā)、響應(yīng)式網(wǎng)站等網(wǎng)站項(xiàng)目制作,到程序開(kāi)發(fā),運(yùn)營(yíng)維護(hù)。成都創(chuàng)新互聯(lián)公司2013年至今到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來(lái)保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選成都創(chuàng)新互聯(lián)公司。

    前言

    動(dòng)畫(huà)是使可視化更具吸引力和用戶吸引力的好方法。它幫助我們以有意義的方式展示數(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)單的線性圖并在其中顯示動(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()

    輸出 :

    如何使用Python創(chuàng)建條形圖追趕動(dòng)畫(huà)

    同樣,你也可以使用 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ù)制作多種類型的動(dòng)畫(huà):

    線性圖動(dòng)畫(huà)

    在這個(gè)例子中,我們將創(chuàng)建一個(gè)簡(jiǎn)單的線性圖,它將顯示一條線的動(dòng)畫(huà)。同樣,使用 FuncAnimation,我們可以創(chuàng)建多種類型的動(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創(chuàng)建條形圖追趕動(dòng)畫(huà)

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

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

    輸出:

    如何使用Python創(chuàng)建條形圖追趕動(dòng)畫(huà)

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

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“如何使用Python創(chuàng)建條形圖追趕動(dòng)畫(huà)”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司,,關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

本文標(biāo)題:如何使用Python創(chuàng)建條形圖追趕動(dòng)畫(huà)-創(chuàng)新互聯(lián)
瀏覽地址:http://chinadenli.net/article20/deecjo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、網(wǎng)站內(nèi)鏈、網(wǎng)站改版品牌網(wǎng)站建設(shè)、商城網(wǎng)站、Google

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作