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)畫,而是從我們傳遞的一系列圖形中創(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)態(tài)線性圖形
在這個(gè)例子中,我們正在創(chuàng)建一個(gè)簡(jiǎn)單的線性圖,它將顯示一條直線的動(dòng)畫。同樣,使用FuncAnimation,我們可以創(chuàng)建許多類型的動(dòng)畫視覺(jué)表示。我們只需要在一個(gè)函數(shù)中定義我們的動(dòng)畫,然后用合適的參數(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畫實(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使用Flask框架同時(shí)上傳多個(gè)文件的方法
這篇文章主要介紹了Python使用Flask框架同時(shí)上傳多個(gè)文件的方法,實(shí)例分析了Python中Flask框架操作文件實(shí)現(xiàn)上傳的技巧,需要的朋友可以參考下2015-03-03
python3實(shí)現(xiàn)windows下同名進(jìn)程監(jiān)控
這篇文章主要為大家詳細(xì)介紹了python3實(shí)現(xiàn)windows下同名進(jìn)程監(jiān)控,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06
python實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)的方法
這篇文章主要介紹了python實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)的方法,涉及Python中os模塊及codecs模塊的相關(guān)使用技巧,需要的朋友可以參考下2015-05-05
python PrettyTable模塊的安裝與簡(jiǎn)單應(yīng)用
prettyTable 是一款很簡(jiǎn)潔但是功能強(qiáng)大的第三方模塊,主要是將輸入的數(shù)據(jù)轉(zhuǎn)化為格式化的形式來(lái)輸出,這篇文章主要介紹了python PrettyTable模塊的安裝與簡(jiǎn)單應(yīng)用,感興趣的小伙伴們可以參考一下2019-01-01
python區(qū)塊鏈持久化和命令行接口實(shí)現(xiàn)簡(jiǎn)版
這篇文章主要為大家介紹了python區(qū)塊鏈持久化和命令行接口實(shí)現(xiàn)簡(jiǎn)版,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05

