Python 與數據資料分析2.2-Matplotlib.pyplot 之動畫

46 篇文章 1 订阅
7 篇文章 0 订阅

“Talk is cheap. Show me the code.”
― Linus Torvalds

老子第41章
上德若谷
大白若辱
大方無隅
大器晚成
大音希聲
大象無形
道隱無名

拳打千遍, 身法自然

110_1_高中週期性課程: Python程式入門與資料分析初探, 道明高中

本系列文章之連結

  • Python程式與數據資料分析1 link
  • Python程式與數據資料分析1.1 Kaggle站免費教學的路徑圖 link
  • Python 與數據資料分析2-資料視覺化-Matplotlib.pyplot 入門 link
  • Python 與數據資料分析3.1-資料視覺化-基本圖表類型 link
  • Python 與數據資料分析3.2-資料視覺化-從 seabon 的函數分類來看 link
  • Python與資料分析3.3-資料視覺化-seaborn 補充 link
  • Python與資料分析4-資料視覺化-鳶尾花 link
  • Python與資料分析 5-入門級競賽分析-鐵達尼號 link


一般在初學 Matplotlib 時, 會發現有關動畫控制的部分, 在網路上較難找到入門的說明, 這篇文章, 主要提供整合各方資源幾個較入門的例子.

最簡單的 pyplot 的動畫例子1-使用 plt.pause()

官網 pyplot 的動畫最基本的例子還是有點複雜, 會分散初學者的注意, 在一些旁枝末節上,

以下我們先給出第一個最最基本的例子, 不使用物件導向的寫法, 使用 pyplot 的基本畫法.

使用 plt.pause() 做出動畫,
優點: 簡單立即實現動畫效果,
缺點:

  • 官網說明到, 此種方式, 效能不高, 只適合簡單的狀況.
  • 無法存成 影片檔, 只能借助外部的軟體錄下來(例如免費的oCam),
    如果想要用 matplotlib 的指令存成 影片檔, 需用另一種做法, 可以使用 matplotlib.animation.FuncAnimation(), 可以看本文後面.

我們參考 stackoverflow
Ref: How to plot additional points on the top of scatter plot?
https://stackoverflow.com/questions/44505762/how-to-plot-additional-points-on-the-top-of-scatter-plot link

以下我們先給出第一個最最基本的例子, 不使用物件導向的寫法,
簡單使用多個 plt.plot(), 中間插入 plt.pause(), 就可以產生動畫效果.
須注意, 圖框的範圍須明確指定,
使用 plt.xlim(-2*np.pi, 2*np.pi), plt.ylim(-2, 2),
指定 x, y 軸各自的範圍大小.

以下的例子, 使用 for, 依序畫出 ( x 1 , s i n ( x 1 ) ) , ( x 2 , s i n ( x 2 ) ) , ⋯   , ( x n , s i n ( x n ) ) (x_1, sin(x_1)), (x_2, sin(x_2)), \cdots, (x_n, sin(x_n)) (x1,sin(x1)),(x2,sin(x2)),,(xn,sin(xn)) 各點, plot 每個點之間使用 plt.pause(1), 間格1秒,

造成 sin 函數的點依序出現, 產生動畫的效果.

# By P-J Lai MATH NKNU 20211214
# 最簡單的寫法 1, 非物件導向, 使用多個 plot(),
# 中間插入 pause()
# pyplot_animation_pause()_simply_1.py

# Ref: How to plot additional points on the top of scatter plot?
# https://stackoverflow.com/questions/44505762/how-to-plot-additional-points-on-the-top-of-scatter-plot


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-2*np.pi, 2*np.pi, 20)

plt.xlim(-2*np.pi, 2*np.pi)
plt.ylim(-2, 2)


for i in range( len(x)):
    plt.plot( x[i], np.sin(x[i]), 'ro')
    plt.pause(1)

plt.show()

pyplot_animation_pause()_simply_1

最簡單的 pyplot 的動畫例子2-使用 plt.pause()

我們修改 stackoverflow 第二個例子
Ref: How to plot additional points on the top of scatter plot? link

一樣不使用物件導向的寫法, 使用 pyplot 的基本畫法.

以下我們給出我們修改的第二個最基本的例子, 除了點可以依序出現, 也可以讓註解文字及箭號依序出現:


# How to plot additional points on the top of scatter plot?
# https://stackoverflow.com/questions/44505762/how-to-plot-additional-points-on-the-top-of-scatter-plot

import matplotlib.pyplot as plt
import numpy as np

from matplotlib import pyplot as plt
from statistics import *

bill = [34.00, 108.00, 64.00, 88.00, 99.00, 51.00]
tip = [ 5.00,  17.00,  11.00, 8.00,  14.00, 5.00]

bill.sort()
tip.sort()

print(mean(bill))
print(mean(tip))
plt.scatter(bill, tip)
plt.pause(2)
plt.scatter([mean(bill)], [mean(tip)])
plt.pause(2)
#ax.annotate("mean(bill) v.s. mean(tip)",(mean(bill), mean(tip))  )
plt.annotate("mean(bill) v.s. mean(tip)",(mean(bill), mean(tip)), xytext=(mean(bill)-20, mean(tip)+3), arrowprops=dict(facecolor='black', shrink=0.05)  )
plt.show()

ax.plot_添加點_箭號_2
ax.plot_添加點_箭號_2.gif

官網 pyplot 的動畫例子-動態熱力圖使用 plt.pause()

以下是官網 pyplot 的動畫最基本的例子:
原文說明, 這個例子的作法, 適用最基本簡單的方法, 只適合簡單低耗效能的例子, 他的方法是持續更新 ax 的二維點的資料, 使用 imshow() 呈現這些二維點, 用 plt.pause(0.1) 使得更新之間, 間格 0.1秒, 造成動畫的感覺.

"""
================
pyplot animation
================

Generating an animation by calling `~.pyplot.pause` between plotting commands.

The method shown here is only suitable for simple, low-performance use.  For
more demanding applications, look at the :mod:`.animation` module and the
examples that use it.

Note that calling `time.sleep` instead of `~.pyplot.pause` would *not* work.
"""

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(19680801)
data = np.random.random((50, 50, 50))

fig, ax = plt.subplots()

for i in range(len(data)):
    ax.cla()
    ax.imshow(data[i])
    ax.set_title("frame {}".format(i))
    # Note that using time.sleep does *not* work here!
    plt.pause(0.1)

使用 matplotlib.animation.FuncAnimation()

需載入
import matplotlib.animation as animation
再下, 例如:

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

Matplotlib 的設定檔

matplotlib.get_configdir()
matplotlib.matplotlib_fname()
matplotlib.rc_params()

# 張若愚 5.1.5

import matplotlib.pyplot as plt
import matplotlib
print(matplotlib.get_configdir())
##C:\Users\user\.matplotlib

print(matplotlib.matplotlib_fname())
##C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\mpl-data\matplotlibrc

print(matplotlib.rc_params())
##_internal.classic_mode: False
##agg.path.chunksize: 0
##animation.avconv_args: []
##animation.avconv_path: avconv
##animation.bitrate: -1
##animation.codec: h264
##,,,
##,,,,
##ytick.labelsize: medium
##ytick.left: True
##ytick.major.left: True
##ytick.major.pad: 3.5
##ytick.major.right: True
##ytick.major.size: 3.5
##ytick.major.width: 0.8
##ytick.minor.left: True
##ytick.minor.pad: 3.4
##ytick.minor.right: True
##ytick.minor.size: 2.0
##ytick.minor.visible: False
##ytick.minor.width: 0.6
##ytick.right: False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值