乱人伦 国语对白海角社区,五月激情丁香婷婷综合中文字幕,欧美伊人婷婷久久五月综合,亚洲精品无amm毛片,亚洲男人第一无码AV网站,国产日韩欧美丝袜一区二区,亚洲一区精品在线观看

利用Python的matplotlib库绘制动态图形-666彩票官方版APP下载K

利用Python的matplotlib库绘制动态图形

2026-01-16 06:49:50投稿人:AG視訊實(shí)力帶人回血(益陽(yáng))有限公司圍觀763 評(píng)論

利用Python的matplotlib庫(kù)繪制動(dòng)態(tài)圖形

一、python 繪制動(dòng)畫(huà)圖

python繪制動(dòng)態(tài)圖形是數(shù)據(jù)可視化更直觀 、更好看的一種方式 ,matplotlib工具包是常用的繪圖工具 ,也可以用來(lái)繪制動(dòng)態(tài)圖形 。本文介紹四種繪制動(dòng)態(tài)圖形的方法,包括生成圖形的代碼和動(dòng)態(tài)圖形演示示例 。

用matplotlib工具包創(chuàng)建動(dòng)畫(huà)圖有兩種方法 :

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

動(dòng)畫(huà)柱狀圖,使用FuncAnimation() 函數(shù)

代碼如下 :

from matplotlib import pyplot as pltfrom matplotlib.animation import FuncAnimation, writersimport 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()

如下圖:


橫向柱狀跑圖 (Horizontal Bar Chart Race) ,使用FuncAnimation() 函數(shù)

以下代碼是繪制世界1500年-2018年主要城市人口變化橫向柱狀跑圖 ,需要數(shù)據(jù)集文件city_populations.csv評(píng)論區(qū)留言 。

程序代碼如下 :

import pandas as pdimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerfrom matplotlib.animation import FuncAnimationdf = 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() / 200for 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 stylesax.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, ' ',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()



散點(diǎn)圖動(dòng)畫(huà) ,使用FuncAnimation()函數(shù)

在本例中, 使用random 數(shù)據(jù)和自定義函數(shù)animation_func()

from matplotlib import pyplot as pltfrom matplotlib.animation import FuncAnimationimport randomimport numpy as npx = []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()

如下圖:


使用 pause() 函數(shù)繪制動(dòng)態(tài)直線

matplotlib工具包的pyplot模塊中有pause()函數(shù) ,可用來(lái)設(shè)置時(shí)間間隔參數(shù),達(dá)到繪制直線的動(dòng)畫(huà)效果。

代碼如下 :

from matplotlib import pyplot as pltx = []y = []for i in range(100):x.append(i)y.append(i)# Mention x and y limits to define their rangeplt.xlim(0, 100)plt.ylim(0, 100)# Ploting graphplt.plot(x, y, color = 'green')plt.pause(0.01)plt.show()

如下圖