使用matplotlib動態(tài)刷新指定曲線實(shí)例
我就廢話不多說啦,還是直接看代碼吧!
from matplotlib import pyplot as plt import numpy as np x = np.linspace(1, 100, 20) y = x *2 +3 fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.scatter(x, y) plt.ion() for i in range(10): y = x*i*0.1 + i try: ax.lines.remove(lines[0]) except Exception: pass lines = ax.plot(x ,y) plt.pause(0.1)
補(bǔ)充知識:用Python的matplotlib庫動態(tài)顯示不斷增長的數(shù)據(jù)
"""
Created on Mon Dec 07 16:34:10 2015
@author: SuperWang
"""
import matplotlib.pyplot as plt
import numpy as np
fig,ax=plt.subplots()
fig2,ax2=plt.subplots()
y1=[]
y2=[]
for i in range(50):
y1.append(np.sin(i))
y2.append(np.cos(i))
ax.cla()
ax.set_title("Loss")
ax.set_xlabel("Iteration")
ax.set_ylabel("Loss")
ax.set_xlim(0,55)
ax.set_ylim(-1,1)
ax.grid()
ax.plot(y1,label='train')
ax.plot(y2,label='test')
ax.legend(loc='best')
ax2.cla()
ax2.set_title("Loss")
ax2.set_xlabel("Iteration")
ax2.set_ylabel("Loss")
ax2.set_xlim(0,55)
ax2.set_ylim(-1,1)
ax2.grid()
ax2.plot(y1,label='train')
ax2.plot(y2,label='test')
ax2.legend(loc='best')
plt.pause(1)
要解決的問題如標(biāo)題所示,原理很簡單,就是當(dāng)數(shù)據(jù)增長時(shí),不斷清空以前的繪畫內(nèi)容,然后把現(xiàn)有的數(shù)據(jù)重新畫出來(數(shù)據(jù)是胡亂生成的)。
具體過程如下:
fig,ax=plt.subplots() 產(chǎn)生一個figure對象和一個axis對象。figure相當(dāng)于一個窗口,而axis相當(dāng)于一個畫布。此句也可以用兩句生成,即fig=plt.figure(num),括號中的參數(shù)是figure的ID,如果只需創(chuàng)建一個figure對象,那么可以省略。然后ax=fig.subplot(1,1,1),subplot()的具體用法可以去google或百度一下。ax.cla()就是在新數(shù)據(jù)到來時(shí),先把之前的繪制的內(nèi)容清空,接下來,ax.set_title(“Loss”),ax.set_xlabel(“Iteration”),ax.set_ylabel(“Loss”)都很簡單,見名知意。ax.set_xlim(0,55),ax.set_ylim(-1,1)分別用來設(shè)置x軸和y軸的兩個端點(diǎn)。ax.grid()給畫布加上網(wǎng)格。ax.plot(y1,label='train'),ax.plot(y2,label='test')這兩句是實(shí)際的繪制命令,其中,參數(shù)label是為以后生成圖例用的。ax2.legend(loc='best')用來生成圖例,loc參數(shù)代表圖例位置location,而value:‘best'是其中的一種選擇,除此之外,還有左上角等其他選項(xiàng)。最后,plt.pause(1)是為了顯示上更直觀,故意每繪制一次,暫停1秒,注意,這里的單位是秒。如果是實(shí)際的應(yīng)用,而數(shù)據(jù)生成的過程又比較慢,此句完全可以省略。
這段代碼中創(chuàng)建了兩個窗口,在實(shí)驗(yàn)過程中,我發(fā)現(xiàn)只能有一個窗口被選中,即用鼠標(biāo)點(diǎn)擊哪個窗口,哪個窗口會動態(tài)地顯示繪畫過程,而另一個保持不動。
繪畫過程截圖如下:

以上這篇使用matplotlib動態(tài)刷新指定曲線實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
淺析Python 抽象工廠模式的優(yōu)缺點(diǎn)
簡單介紹Python的Tornado框架中的協(xié)程異步實(shí)現(xiàn)原理

