亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

用 Matplotlib 庫生成動(dòng)畫圖表

call_me_R / 1686人閱讀

摘要:相對于靜態(tài)圖表,人類總是容易被動(dòng)畫和交互式圖表所吸引??梢允褂幂p松生成圖表直方圖功率譜,條形圖,錯(cuò)誤圖表,散點(diǎn)圖等。然而,也有一些方面落后于同類的庫。動(dòng)畫使用一組固定的對象。稍后將用數(shù)據(jù)對行對象進(jìn)行填充?,F(xiàn)在用將它們轉(zhuǎn)換為動(dòng)畫。

翻譯:瘋狂的技術(shù)宅
https://towardsdatascience.co...


更多文章請關(guān)注微信公眾號:硬核智能


動(dòng)畫是一種展示現(xiàn)象的有趣方式。相對于靜態(tài)圖表,人類總是容易被動(dòng)畫和交互式圖表所吸引。在描述多年來的股票價(jià)格、過去十年的氣候變化、季節(jié)性和趨勢等時(shí)間序列數(shù)據(jù)時(shí),動(dòng)畫更有意義,因?yàn)槲覀兛梢钥吹教囟ǖ膮?shù)是怎樣隨時(shí)間變化的。

上面的圖是雨滴的模擬并且已經(jīng)使用 Matplotlib 庫實(shí)現(xiàn),該庫是一個(gè)廣為人知的祖父級別的 python 可視化包。 Matplotlib 通過對 50 個(gè)散點(diǎn)的比例和透明度進(jìn)行設(shè)置來模擬雨滴。今天,Python 擁有大量強(qiáng)大的可視化工具,如 Plotly、Bokeh、Altair等等。這些庫能夠?qū)崿F(xiàn)最先進(jìn)的動(dòng)畫和交互特性。盡管如此,本文的目的是強(qiáng)調(diào)這個(gè)庫的另一個(gè)方面,這個(gè)方面沒有人進(jìn)行過太多的探索,這就是動(dòng)畫。


概述

Matplotlib 是一個(gè)廣受歡迎的 Python 2D 繪圖庫。很多人都是從 Matplotlib 開始數(shù)據(jù)可視化之旅的??梢允褂胢atplotlib輕松生成圖表、直方圖、功率譜,條形圖,錯(cuò)誤圖表,散點(diǎn)圖等。它還與 Pandas 和 Seaborn 等庫無縫集成,創(chuàng)造出更加復(fù)雜的可視化效果。

matplotlib 的優(yōu)點(diǎn)是:

它的設(shè)計(jì)類似于 MATLAB,因此很容易在在兩者之間切換。

在后端進(jìn)行渲染。

可以重現(xiàn)任何圖表(需要一點(diǎn)努力)。

已經(jīng)存在了十多年,擁有龐大的用戶群。

然而,也有一些方面 Matplotlib 落后于同類的庫。

Matplotlib 有一個(gè)過于冗長的規(guī)則 API。

有時(shí)候風(fēng)格很差。

對 Web 和交互式圖表的支持不佳。

對于大型復(fù)雜數(shù)據(jù)而言通常很慢。

這份復(fù)習(xí)資料是來自 Datacamp 的 Matplotlib 小抄,你可以通過它來提高自己的基礎(chǔ)知識(shí)。


動(dòng)畫

Matplotlib 的 animation 基類負(fù)責(zé)處理動(dòng)畫部分。它提供了一個(gè)構(gòu)建動(dòng)畫功能的框架。使用下面兩個(gè)接口來實(shí)現(xiàn):

FuncAnimation 通過重復(fù)調(diào)用函數(shù) func 來產(chǎn)生動(dòng)畫。

ArtistAnimation: 動(dòng)畫使用一組固定的 Artist 對象。

但是,在這兩個(gè)接口中,FuncAnimation 是最方便使用的。你可以通過閱讀文檔 得到的更多信息,因?yàn)槲覀冎魂P(guān)注 FuncAnimation 工具。

要求

安裝 numpymatplotlib 。

要將動(dòng)畫保存為 mp4 或 gif,需要安裝 ffmpegimagemagick。

準(zhǔn)備好之后,我們就可以在 Jupyter note 中開始創(chuàng)建第一個(gè)動(dòng)畫了??梢詮?Github 得到本文的代碼。

基本動(dòng)畫:移動(dòng)的正弦波

我們先用 FuncAnimation 創(chuàng)建一個(gè)在屏幕上移動(dòng)的正弦波的動(dòng)畫。動(dòng)畫的源代碼來自 Matplotlib 動(dòng)畫教程。首先看一下輸出,然后我們會(huì)分析代碼以了解幕后的原理。

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use("seaborn-pastel")


fig = plt.figure()
ax = plt.axes(xlim=(0, 4), ylim=(-2, 2))
line, = ax.plot([], [], lw=3)

def init():
    line.set_data([], [])
    return line,
def animate(i):
    x = np.linspace(0, 4, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

anim = FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

anim.save("sine_wave.gif", writer="imagemagick")

在第(7-9)行中,我們只需在圖中創(chuàng)建一個(gè)帶有單個(gè)軸的圖形窗口。然后創(chuàng)建一個(gè)空的行對象,它實(shí)際上是動(dòng)畫中要修改的對象。稍后將用數(shù)據(jù)對行對象進(jìn)行填充。

在第(11-13)行中,我們創(chuàng)建了 init 函數(shù),它將使動(dòng)畫開始。 init 函數(shù)對數(shù)據(jù)進(jìn)行初始化并設(shè)置軸限制。

在第(14-18)行中,我們最終定義了動(dòng)畫函數(shù),該函數(shù)將幀編號( i )作為參數(shù)并創(chuàng)建正弦波(或任何其他動(dòng)畫),這取決于 i 的值。此函數(shù)返回一個(gè)已修改的繪圖對象的元組,它告訴動(dòng)畫框架哪些部分應(yīng)該屬于動(dòng)畫。

在第 20 行中,我們創(chuàng)建了實(shí)際的動(dòng)畫對象。 blit 參數(shù)確保只重繪那些已經(jīng)改變的圖塊。

這是在 Matplotlib 中創(chuàng)建動(dòng)畫的基本方法。通過對代碼進(jìn)行一些調(diào)整,可以創(chuàng)建有趣的可視化圖表。接下來看看更多的可視化案例。


一個(gè)不斷增長的線圈

同樣,在 GeeksforGeeks 中有一個(gè)很好的例子?,F(xiàn)在讓我們在 matplotlib 的 animation 類的幫助下創(chuàng)建一個(gè)緩慢展開的動(dòng)圈。該代碼非常類似于正弦波圖,只需稍作調(diào)整即可。

import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
import numpy as np 
plt.style.use("dark_background")

fig = plt.figure() 
ax = plt.axes(xlim=(-50, 50), ylim=(-50, 50)) 
line, = ax.plot([], [], lw=2) 

# initialization function 
def init(): 
    # creating an empty plot/frame 
    line.set_data([], []) 
    return line, 

# lists to store x and y axis points 
xdata, ydata = [], [] 

# animation function 
def animate(i): 
    # t is a parameter 
    t = 0.1*i 
    
    # x, y values to be plotted 
    x = t*np.sin(t) 
    y = t*np.cos(t) 
    
    # appending new points to x, y axes points list 
    xdata.append(x) 
    ydata.append(y) 
    line.set_data(xdata, ydata) 
    return line, 
    
# setting a title for the plot 
plt.title("Creating a growing coil with matplotlib!") 
# hiding the axis details 
plt.axis("off") 

# call the animator     
anim = animation.FuncAnimation(fig, animate, init_func=init, 
                            frames=500, interval=20, blit=True) 

# save the animation as mp4 video file 
anim.save("coil.gif",writer="imagemagick") 


實(shí)時(shí)更新圖表

在繪制動(dòng)態(tài)數(shù)量(如庫存數(shù)據(jù),傳感器數(shù)據(jù)或任何其他時(shí)間相關(guān)數(shù)據(jù))時(shí),實(shí)時(shí)更新的圖表會(huì)派上用場。我們繪制了一個(gè)簡單的圖表,當(dāng)有更多數(shù)據(jù)被輸入系統(tǒng)時(shí),該圖表會(huì)自動(dòng)更新。下面讓我們繪制一家假想公司在一個(gè)月內(nèi)的股票價(jià)格。

# importing libraries
import matplotlib.pyplot as plt
import matplotlib.animation as animation


fig = plt.figure()
# creating a subplot 
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    data = open("stock.txt","r").read()
    lines = data.split("
")
    xs = []
    ys = []
   
    for line in lines:
        x, y = line.split(",") # Delimiter is comma    
        xs.append(float(x))
        ys.append(float(y))
    
    ax1.clear()
    ax1.plot(xs, ys)

    plt.xlabel("Date")
    plt.ylabel("Price")
    plt.title("Live graph with matplotlib")    
    
    
ani = animation.FuncAnimation(fig, animate, interval=1000) 
plt.show()

現(xiàn)在,打開終端并運(yùn)行 python 腳本。你將得到如下圖所示的圖表,該圖表會(huì)自動(dòng)更新:

這里的間隔是 1000 毫秒或一秒。


3D 圖動(dòng)畫

創(chuàng)建 3D 圖形是很常見的,但如果我們想要為這些圖形的視角設(shè)置動(dòng)畫,該怎么辦呢?我們的想法是更改攝像機(jī)視圖,然后用每個(gè)生成的圖像來創(chuàng)建動(dòng)畫。在 Python Graph Gallery 上有一個(gè)很好的例子。

在與 jupyter notebook 相同的目錄中創(chuàng)建名為 volcano 的文件夾。所有圖片文件都將存儲(chǔ)在這里,然后將在動(dòng)畫中使用。

# library
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

# Get the data (csv file is hosted on the web)
url = "https://python-graph-gallery.com/wp-content/uploads/volcano.csv"
data = pd.read_csv(url)

# Transform it to a long format
df=data.unstack().reset_index()
df.columns=["X","Y","Z"]

# And transform the old column name in something numeric
df["X"]=pd.Categorical(df["X"])
df["X"]=df["X"].cat.codes

# We are going to do 20 plots, for 20 different angles
for angle in range(70,210,2):

# Make the plot
    fig = plt.figure()
    ax = fig.gca(projection="3d")
    ax.plot_trisurf(df["Y"], df["X"], df["Z"], cmap=plt.cm.viridis, linewidth=0.2)

    ax.view_init(30,angle)

    filename="Volcano/Volcano_step"+str(angle)+".png"
    plt.savefig(filename, dpi=96)
    plt.gca()

這將會(huì)在 Volcano 文件夾中創(chuàng)建多個(gè) PNG 文件?,F(xiàn)在用 ImageMagick 將它們轉(zhuǎn)換為動(dòng)畫。打開終端并切換到 Volcano 目錄下輸入以下命令:

convert -delay 10 Volcano*.png animated_volcano.gif


使用 Celluloid 模塊創(chuàng)建的動(dòng)畫

Celluloid 是一個(gè)Python模塊,它簡化了在 matplotlib 中創(chuàng)建動(dòng)畫的過程。這個(gè)庫創(chuàng)建一個(gè) matplotlib 圖,并從中再創(chuàng)建一個(gè) Camera。然后重新處理數(shù)據(jù),并在創(chuàng)建每個(gè)幀后,用 camera 拍攝快照。最后創(chuàng)建包含所有幀的動(dòng)畫。

安裝
pip install celluloid

以下是使用 Celluloid 模塊的一些示例。

Minimal
from matplotlib import pyplot as plt
from celluloid import Camera

fig = plt.figure()
camera = Camera(fig)
for i in range(10):
    plt.plot([i] * 10)
    camera.snap()
animation = camera.animate()
animation.save("celluloid_minimal.gif", writer = "imagemagick")

Subplot
import numpy as np
from matplotlib import pyplot as plt
from celluloid import Camera

fig, axes = plt.subplots(2)
camera = Camera(fig)
t = np.linspace(0, 2 * np.pi, 128, endpoint=False)
for i in t:
    axes[0].plot(t, np.sin(t + i), color="blue")
    axes[1].plot(t, np.sin(t - i), color="blue")
    camera.snap()
    
animation = camera.animate()  
animation.save("celluloid_subplots.gif", writer = "imagemagick")

Legend
import matplotlib
from matplotlib import pyplot as plt
from celluloid import Camera

fig = plt.figure()
camera = Camera(fig)
for i in range(20):
    t = plt.plot(range(i, i + 5))
    plt.legend(t, [f"line {i}"])
    camera.snap()
animation = camera.animate()
animation.save("celluloid_legends.gif", writer = "imagemagick")


總結(jié)

動(dòng)畫有助于突出顯示無法通過靜態(tài)圖表輕松傳達(dá)的某些功能。盡管如此,不必要的過度使用有時(shí)會(huì)使事情復(fù)雜化,應(yīng)該明智地使用數(shù)據(jù)可視化中的每個(gè)功能以產(chǎn)生最佳效果。

更多文章請關(guān)注微信公眾號:硬核智能

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/43671.html

相關(guān)文章

  • Matplotlib 生成動(dòng)畫圖表

    摘要:相對于靜態(tài)圖表,人類總是容易被動(dòng)畫和交互式圖表所吸引??梢允褂幂p松生成圖表直方圖功率譜,條形圖,錯(cuò)誤圖表,散點(diǎn)圖等。然而,也有一些方面落后于同類的庫。動(dòng)畫使用一組固定的對象。稍后將用數(shù)據(jù)對行對象進(jìn)行填充?,F(xiàn)在用將它們轉(zhuǎn)換為動(dòng)畫。 翻譯:瘋狂的技術(shù)宅https://towardsdatascience.co... showImg(https://segmentfault.com/img...

    不知名網(wǎng)友 評論0 收藏0
  • 快速入門 Matplotlib 繪圖

    摘要:概述是使用開發(fā)的一個(gè)繪圖庫,是界進(jìn)行數(shù)據(jù)可視化的首選庫??梢酝ㄟ^圖形示例來快速瀏覽所有支持的圖形。最后,調(diào)用把繪制好的圖形顯示出來。對應(yīng)于三個(gè)參數(shù),表示行,表示列,表示位置。因此,表示在圖表中總共有個(gè)圖形,當(dāng)前新增的圖形添加到位置。 showImg(https://segmentfault.com/img/bV6EPD?w=542&h=130); 概述 Matplotlib 是使用 P...

    Hujiawei 評論0 收藏0
  • Python繪制精美圖表之雙柱形圖

    摘要:圖表是比干巴巴的表格更直觀的表達(dá),簡潔有力。當(dāng)我們想關(guān)注比數(shù)值本身更多的信息像數(shù)值的變化對比或異常,圖表就非常有用了。把數(shù)值轉(zhuǎn)化為圖片要依賴第三方庫的幫忙,在之中最好的圖表庫叫。 圖表是比干巴巴的表格更直觀的表達(dá),簡潔、有力。工作中經(jīng)常遇到的場景是,有一些數(shù)值需要定時(shí)的監(jiān)控,比如服務(wù)器的連接數(shù)、活躍用戶數(shù)、點(diǎn)擊某個(gè)按鈕的人數(shù),并且通過郵件或者網(wǎng)頁展示出來。當(dāng)我們想關(guān)注比數(shù)值本身更多的信...

    beita 評論0 收藏0
  • Python學(xué)習(xí)之路14-生成數(shù)據(jù)

    摘要:小結(jié)本篇主要講述了如何生成數(shù)據(jù)集以及如何對其進(jìn)行可視化如何使用創(chuàng)建簡單的圖表如果使用散點(diǎn)圖來探索隨機(jī)漫步過程如何使用創(chuàng)建直方圖,以及如何使用直方圖來探索同時(shí)擲兩個(gè)面數(shù)不同的骰子的結(jié)果。 《Python編程:從入門到實(shí)踐》筆記。從本篇起將用三篇的篇幅介紹如何用Python進(jìn)行數(shù)據(jù)可視化。 1. 前言 從本篇開始,我們將用三篇的篇幅來初步介紹如何使用Python來進(jìn)行數(shù)據(jù)可視化操作。本篇的...

    wanglu1209 評論0 收藏0
  • Python學(xué)習(xí)筆記:數(shù)據(jù)可視化(一)

    摘要:當(dāng)數(shù)據(jù)發(fā)生變化時(shí),這種演變過程隨之發(fā)生。是一種統(tǒng)計(jì)報(bào)告圖,由一系列高度不等的縱向條紋或線段表示數(shù)據(jù)分布的情況。 showImg(https://segmentfault.com/img/bVbnkP1?w=751&h=558); python相關(guān) 基礎(chǔ)概念 數(shù)據(jù):離散的,客觀事實(shí)的數(shù)字表示 信息:處理后的數(shù)據(jù),為實(shí)際問題提供答案   - 為數(shù)據(jù)提供一種關(guān)系或一個(gè)關(guān)聯(lián)后,數(shù)據(jù)就成了信...

    Crazy_Coder 評論0 收藏0

發(fā)表評論

0條評論

call_me_R

|高級講師

TA的文章

閱讀更多
最新活動(dòng)
閱讀需要支付1元查看
<