欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python使用Matplotlib實現(xiàn)創(chuàng)建動態(tài)圖形

 更新時間:2024年02月25日 08:41:03   作者:python收藏家  
動態(tài)圖形是使可視化更具吸引力和用戶吸引力的好方法,它幫助我們以有意義的方式展示數(shù)據(jù)可視化,本文將利用Matplotlib實現(xiàn)繪制一些常用動態(tài)圖形,希望對大家有所幫助

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

使用Matplotlib創(chuàng)建動態(tài)圖形有兩種方法:

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

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

matplotlib庫的pyplot模塊中的pause()函數(shù)用于暫停參數(shù)中提到的間隔秒??紤]下面的例子,我們將使用matplotlib創(chuàng)建一個簡單的線性圖,并在其中顯示Animation:

  • 創(chuàng)建兩個數(shù)組,X和Y,并存儲從1到100的值。
  • 使用plot()函數(shù)繪制X和Y。
  • 添加pause()函數(shù),并設(shè)置適當(dāng)?shù)臅r間間隔
  • 運行程序,你會看到動態(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ù)

這個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ù)制作多種類型的動畫:

動態(tài)線性圖形

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

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

動態(tài)散點圖

在這個例子中,我們將在python中使用random函數(shù)動態(tài)散點圖。我們將迭代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()

動態(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實現(xiàn)創(chuàng)建動態(tài)圖形的詳細(xì)內(nèi)容,更多關(guān)于Python Matplotlib動態(tài)圖形的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python圖像處理-利用一行代碼實現(xiàn)灰度圖摳圖

    python圖像處理-利用一行代碼實現(xiàn)灰度圖摳圖

    這篇文章主要介紹了python圖像處理-利用一行代碼實現(xiàn)灰度圖摳圖,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • Python使用Marshmallow輕松實現(xiàn)序列化和反序列化

    Python使用Marshmallow輕松實現(xiàn)序列化和反序列化

    這篇文章主要為大家詳細(xì)介紹了Python如何使用Marshmallow輕松實現(xiàn)序列化和反序列化,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下
    2025-03-03
  • Python解析壓縮包內(nèi)部文件的后綴名并分類存放

    Python解析壓縮包內(nèi)部文件的后綴名并分類存放

    這篇文章主要為大家詳細(xì)介紹了如何使用Python解析壓縮包內(nèi)部文件的后綴名并分類存放,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-12-12
  • python計算圓周率pi的方法

    python計算圓周率pi的方法

    這篇文章主要介紹了python計算圓周率pi的方法,涉及Python針對數(shù)學(xué)運算的相關(guān)技巧,需要的朋友可以參考下
    2015-07-07
  • PyCharm如何配置SSH和SFTP連接遠(yuǎn)程服務(wù)器

    PyCharm如何配置SSH和SFTP連接遠(yuǎn)程服務(wù)器

    這篇文章主要介紹了PyCharm如何配置SSH和SFTP連接遠(yuǎn)程服務(wù)器,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • python安裝pywifi全過程

    python安裝pywifi全過程

    這篇文章主要介紹了python安裝pywifi全過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • Python實例方法、類方法、靜態(tài)方法區(qū)別詳解

    Python實例方法、類方法、靜態(tài)方法區(qū)別詳解

    這篇文章主要介紹了Python實例方法、類方法、靜態(tài)方法區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-09-09
  • Python列表切片操作實例探究(提取復(fù)制反轉(zhuǎn))

    Python列表切片操作實例探究(提取復(fù)制反轉(zhuǎn))

    在Python中,列表切片是處理列表數(shù)據(jù)非常強(qiáng)大且靈活的方法,本文將全面探討Python中列表切片的多種用法,包括提取子列表、復(fù)制列表、反轉(zhuǎn)列表等操作,結(jié)合豐富的示例代碼進(jìn)行詳細(xì)講解
    2024-01-01
  • python3.6 實現(xiàn)AES加密的示例(pyCryptodome)

    python3.6 實現(xiàn)AES加密的示例(pyCryptodome)

    本篇文章主要介紹了python3.6 實現(xiàn)AES加密的示例(pyCryptodome),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01
  • Python的函數(shù)使用詳解

    Python的函數(shù)使用詳解

    大家好,本篇文章主要講的是Python的函數(shù)使用詳解,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12

最新評論