Python使用Matplotlib實(shí)現(xiàn)創(chuàng)建動(dòng)態(tài)圖形
動(dòng)態(tài)圖形是使可視化更具吸引力和用戶吸引力的好方法。它幫助我們以有意義的方式展示數(shù)據(jù)可視化。Python幫助我們使用現(xiàn)有強(qiáng)大的Python庫(kù)創(chuàng)建動(dòng)態(tài)圖形可視化。Matplotlib是一個(gè)非常流行的數(shù)據(jù)可視化庫(kù),通常用于數(shù)據(jù)的圖形表示,也用于使用內(nèi)置函數(shù)的動(dòng)態(tài)圖形。
使用Matplotlib創(chuàng)建動(dòng)態(tài)圖形有兩種方法:
- 使用pause()函數(shù)
- 使用FuncAnimation()函數(shù)
方法1:使用pause()函數(shù)
matplotlib庫(kù)的pyplot模塊中的pause()函數(shù)用于暫停參數(shù)中提到的間隔秒??紤]下面的例子,我們將使用matplotlib創(chuàng)建一個(gè)簡(jiǎn)單的線性圖,并在其中顯示Animation:
- 創(chuàng)建兩個(gè)數(shù)組,X和Y,并存儲(chǔ)從1到100的值。
- 使用plot()函數(shù)繪制X和Y。
- 添加pause()函數(shù),并設(shè)置適當(dāng)?shù)臅r(shí)間間隔
- 運(yùn)行程序,你會(huì)看到動(dòng)態(tài)圖形。
from matplotlib import pyplot as plt x = [] y = [] for i in range(100): x.append(i) y.append(i) # Mention x and y limits to define their range plt.xlim(0, 100) plt.ylim(0, 100) # Plotting graph plt.plot(x, y, color = 'green') plt.pause(0.01) plt.show()
方法2:使用FuncAnimation()函數(shù)
這個(gè)FuncAnimation()函數(shù)本身并不創(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)態(tài)線性圖形
在這個(gè)例子中,我們正在創(chuàng)建一個(gè)簡(jiǎn)單的線性圖,它將顯示一條直線的動(dòng)畫(huà)。同樣,使用FuncAnimation,我們可以創(chuàng)建許多類型的動(dòng)畫(huà)視覺(jué)表示。我們只需要在一個(gè)函數(shù)中定義我們的動(dòng)畫(huà),然后用合適的參數(shù)將其傳遞給FuncAnimation。
from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation import numpy as np x = [] y = [] figure, ax = plt.subplots() # Setting limits for x and y axis ax.set_xlim(0, 100) ax.set_ylim(0, 12) # Since plotting a single graph 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()
動(dòng)態(tài)條形圖
from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation, writers import numpy as np 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 = 5 * i y3 = 3 * i y4 = 2 * i y5 = 6 * i y6 = 3 * i plt.xlabel("Country") plt.ylabel("GDP of Country") plt.bar(["India", "China", "Germany", "USA", "Canada", "UK"], [y1, y2, y3, y4, y5, y6], color = palette) plt.title("Bar Chart Animation") animation = FuncAnimation(fig, animation_function, interval = 50) plt.show()
動(dòng)態(tài)散點(diǎn)圖
在這個(gè)例子中,我們將在python中使用random函數(shù)動(dòng)態(tài)散點(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)態(tài)水平條形圖
import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as ticker from matplotlib.animation import FuncAnimation 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') # polished styles 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, 'The most populous cities in the world from 1500 to 2018', transform=ax.transAxes, size=24, weight=600, ha='left') ax.text(1, 0, 'by @pratapvardhan; credit @jburnmurdoch', 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使用Matplotlib實(shí)現(xiàn)創(chuàng)建動(dòng)態(tài)圖形的詳細(xì)內(nèi)容,更多關(guān)于Python Matplotlib動(dòng)態(tài)圖形的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- python+matplotlib實(shí)現(xiàn)動(dòng)態(tài)繪制圖片實(shí)例代碼(交互式繪圖)
- python之matplotlib學(xué)習(xí)繪制動(dòng)態(tài)更新圖實(shí)例代碼
- python學(xué)習(xí)之使用Matplotlib畫(huà)實(shí)時(shí)的動(dòng)態(tài)折線圖的示例代碼
- Python繪制數(shù)據(jù)動(dòng)態(tài)圖的方法詳解
- Python利用matplotlib實(shí)現(xiàn)制作動(dòng)態(tài)條形圖
- Python實(shí)現(xiàn)動(dòng)態(tài)繪圖的示例詳解
- 使用Python+Matplotlib制作時(shí)序動(dòng)態(tài)圖
相關(guān)文章
python圖像處理-利用一行代碼實(shí)現(xiàn)灰度圖摳圖
這篇文章主要介紹了python圖像處理-利用一行代碼實(shí)現(xiàn)灰度圖摳圖,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05Python使用Marshmallow輕松實(shí)現(xiàn)序列化和反序列化
這篇文章主要為大家詳細(xì)介紹了Python如何使用Marshmallow輕松實(shí)現(xiàn)序列化和反序列化,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下2025-03-03PyCharm如何配置SSH和SFTP連接遠(yuǎn)程服務(wù)器
這篇文章主要介紹了PyCharm如何配置SSH和SFTP連接遠(yuǎn)程服務(wù)器,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05Python實(shí)例方法、類方法、靜態(tài)方法區(qū)別詳解
這篇文章主要介紹了Python實(shí)例方法、類方法、靜態(tài)方法區(qū)別詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09Python列表切片操作實(shí)例探究(提取復(fù)制反轉(zhuǎn))
在Python中,列表切片是處理列表數(shù)據(jù)非常強(qiáng)大且靈活的方法,本文將全面探討Python中列表切片的多種用法,包括提取子列表、復(fù)制列表、反轉(zhuǎn)列表等操作,結(jié)合豐富的示例代碼進(jìn)行詳細(xì)講解2024-01-01python3.6 實(shí)現(xiàn)AES加密的示例(pyCryptodome)
本篇文章主要介紹了python3.6 實(shí)現(xiàn)AES加密的示例(pyCryptodome),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01