用python画动图_Python使用matplotlib画动态图
機(jī)器學(xué)習(xí)需要使用python實現(xiàn)相應(yīng)的算法,因此學(xué)習(xí)了Matplotlib中的畫圖。
當(dāng)然為了能顯示機(jī)器學(xué)習(xí)中每次迭代的效果與收斂速度,需要畫出動態(tài)圖形。
下面給出兩個例子,分別可以畫出動態(tài)條形圖和動態(tài)折線圖(使用兩種不同的方法)。
注意要使用到plt.pause(time)函數(shù)。
動態(tài)條形圖
基本原理是將數(shù)據(jù)放入數(shù)組,然后每次往數(shù)組里面增加一個數(shù),清除之前的圖,重新畫出圖像。
代碼:
Python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
y1 = []
for i in range(50):
y1.append(i) # 每迭代一次,將i放入y1中畫出來
ax.cla() # 清除鍵
ax.bar(y1, label='test', height=y1, width=0.3)
ax.legend()
plt.pause(0.1)
1
2
3
4
5
6
7
8
9
importmatplotlib.pyplotasplt
fig,ax=plt.subplots()
y1=[]
foriinrange(50):
y1.append(i)# 每迭代一次,將i放入y1中畫出來
ax.cla()# 清除鍵
ax.bar(y1,label='test',height=y1,width=0.3)
ax.legend()
plt.pause(0.1)
效果:
動態(tài)折線圖
基本原理是使用一個長度為2的數(shù)組,每次替換數(shù)據(jù)并在原始圖像后追加。
代碼:
Python
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0, 100, 0, 1])
plt.ion()
xs = [0, 0]
ys = [1, 1]
for i in range(100):
y = np.random.random()
xs[0] = xs[1]
ys[0] = ys[1]
xs[1] = i
ys[1] = y
plt.plot(xs, ys)
plt.pause(0.1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
importnumpyasnp
importmatplotlib.pyplotasplt
plt.axis([0,100,0,1])
plt.ion()
xs=[0,0]
ys=[1,1]
foriinrange(100):
y=np.random.random()
xs[0]=xs[1]
ys[0]=ys[1]
xs[1]=i
ys[1]=y
plt.plot(xs,ys)
plt.pause(0.1)
效果:
總結(jié)
以上是生活随笔為你收集整理的用python画动图_Python使用matplotlib画动态图的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows 搭建python 虚拟环
- 下一篇: excel vba 调用webbrows