影片是使可視化更具吸引力和用戶吸引力的好方法,它幫助我們以有意義的方式展示資料可視化,Python 幫助我們使用現有的強大 Python 庫創建影片可視化,Matplotlib是一個非常流行的資料可視化庫,通常用于資料的圖形表示以及使用內置函式的影片,
直接跳到末尾 去評論區領書
🏆 在 Python 中創建條形圖追趕影片(評論區送書)
- 🍖 方法一:使用 pause() 函式
- 🚀 方法二:使用 FuncAnimation() 函式
- 🥋 線性圖影片:
- 🎻 Python 中的條形圖追趕影片
- 🌌 Python 中的散點圖影片:
- 🛹 條形圖追趕的水平移動:
- 🥇 評論區抽粉絲送書啦
使用 Matplotlib 創建影片有兩種方法:
- 使用 pause() 函式
- 使用 FuncAnimation() 函式
🍖 方法一:使用 pause() 函式
在暫停()的matplotlib庫的pyplot模塊在功能上用于暫停為引數提到間隔秒,考慮下面的示例,我們將使用 matplotlib 創建一個簡單的線性圖并在其中顯示影片:
創建 2 個陣列 X 和 Y,并存盤從 1 到 100 的值,
使用 plot() 函式繪制 X 和 Y,
以合適的時間間隔添加 pause() 函式
運行程式,你會看到影片,
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()
輸出 :

同樣,你也可以使用 pause() 函式在各種繪圖中創建影片,
🚀 方法二:使用 FuncAnimation() 函式
這個FuncAnimation() 函式不會自己創建影片,而是從我們傳遞的一系列圖形中創建影片,
語法: FuncAnimation(figure, animation_function, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True,
**kwargs)
現在您可以使用 FuncAnimation 函式制作多種型別的影片:
🥋 線性圖影片:
在這個例子中,我們將創建一個簡單的線性圖,它將顯示一條線的影片,同樣,使用 FuncAnimation,我們可以創建多種型別的影片視覺表示,我們只需要在一個函式中定義我們的影片,然后用合適的引數將它傳遞給FuncAnimation,
Python
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
x = []
y = []
figure, ax = plt.subplots()
# 設定 x 和 y 軸的限制
ax.set_xlim(0, 100)
ax.set_ylim(0, 12)
# 繪制單個圖形
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 中的條形圖追趕影片
在此示例中,我們將創建一個簡單的條形圖影片,它將顯示每個條形的影片,
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("國家")
plt.ylabel("國家GDP")
plt.bar(["印度", "中國", "德國",
"美國", "加拿大", "英國"],
[y1, y2, y3, y4, y5, y6],
color = palette)
plt.title("條形圖影片")
animation = FuncAnimation(fig, animation_function,
interval = 50)
plt.show()
輸出:

🌌 Python 中的散點圖影片:
在這個例子中,我們將使用隨機函式在 python 中影片散點圖,我們將遍歷animation_func并在迭代時繪制 x 和 y 軸的隨機值,
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()
輸出:

🛹 條形圖追趕的水平移動:
在這里,我們將使用城市資料集中的最高人口繪制條形圖競賽,
不同的城市會有不同的條形圖,條形圖追趕將從 1990 年到 2018 年迭代,
我從人口最多的資料集中選擇了最高城市的國家,
需要用到的資料集可以從這里下載: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實戰》
簡介:理論性與實用性兼備,既可作為初學者的入門書籍,也可作為求職者的面試寶典,更可作為職場人士轉崗的實用手冊,本書適合需要全面學習機器學習演算法的初學者、希望掌味訓器學習演算法數學理論的程式員、想轉行從事機器學習演算法的專業人員、對機器學習演算法興趣濃厚的人員、專業培訓機構學員和希望提高 Python 編程水平的程式員,
優點:
🌟1.與周志華撰寫的《機器學習》相比,本書多了對演算法的數學原理詳細嚴謹的推導,
🌟2.與李銳翻譯的《機器學習實戰》相比,本書多了用面向物件思想將演算法模塊化,并且書中代碼在Python 3 環境下運行,
🌟3.為了照顧初學者,本書補充了全書涉及的高等數學、線性代數、概率論與數理統計、Jessen不等式等數學基礎知識,
也有不想抽獎自己買的同學可以參考下面的鏈接
京東自營購買鏈接:
《機器學習入門:基于數學原理的Python實戰》(戴璞微,潘斌)【摘要 書評 試讀】- 京東圖書
當當自營購買鏈接:
《機器學習入門:基于數學原理的Python實戰》(戴璞微)【簡介_書評_在線閱讀】 - 當當圖書
📣 注意:
大家點贊關注,三天后也就是 9月28日 從評論區留言的同學中抽取兩位送書
🌊 行業資料:精品PPT模板幾千套,簡歷模板一千多套
🌊 面試題庫:Java核心知識點大全和面試真題資料
🌊 學習資料:2300套PHP建站原始碼,微信小程式入門資料,Python全集(400集)
如果中獎了聯系不上則視為放棄,可以從下方公眾號里找到作者的聯系方式,回復【資源】獲取上面的資料👇🏻👇🏻👇🏻
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/302965.html
標籤:AI
下一篇:非常受歡迎的15大Python庫
