溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用matplotlib怎么實(shí)現(xiàn)一個數(shù)據(jù)實(shí)時刷新功能

發(fā)布時間:2021-01-05 14:13:50 來源:億速云 閱讀:854 作者:Leah 欄目:開發(fā)技術(shù)

使用matplotlib怎么實(shí)現(xiàn)一個數(shù)據(jù)實(shí)時刷新功能?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

import matplotlib.pyplot as plt
import numpy as np
import threading
import sys
from random import random, randrange
from time import sleep

'''
繪制2x2的畫板
可設(shè)置窗口標(biāo)題和4個子圖標(biāo)題
可更新曲線數(shù)據(jù)
'''
quit_flag = False # 退出標(biāo)志


class Plot2_2(object):
  """ 2x2的畫板 """

  def __init__(self, wtitle='Figure', p1title='1', p2title='2', p3title='3',
         p4title='4'):
    self.sub_title = [p1title, p2title, p3title, p4title] # 4個子圖的標(biāo)題
    self.fig, self.ax = plt.subplots(2, 2) # 創(chuàng)建2X2子圖
    self.fig.subplots_adjust(wspace=0.3, hspace=0.3) # 設(shè)置子圖之間的間距
    self.fig.canvas.set_window_title(wtitle) # 設(shè)置窗口標(biāo)題

    # 子圖字典,key為子圖的序號,value為子圖句柄
    self.axdict = {0: self.ax[0, 0], 1: self.ax[0, 1], 2: self.ax[1, 0], 3: self.ax[1, 1]}

  def showPlot(self):
    """ 顯示曲線 """
    plt.show()

  def setPlotStyle(self, index):
    """ 設(shè)置子圖的樣式,這里僅設(shè)置了標(biāo)題 """
    self.axdict[index].set_title(self.sub_title[index], fontsize=12)

  def updatePlot(self, index, x, y):
    """
    更新指定序號的子圖
    :param index: 子圖序號
    :param x: 橫軸數(shù)據(jù)
    :param y: 縱軸數(shù)據(jù)
    :return:
    """
    # X軸數(shù)據(jù)必須和Y軸數(shù)據(jù)長度一致
    if len(x) != len(y):
      ex = ValueError("x and y must have same first dimension")
      raise ex

    self.axdict[index].cla() # 清空子圖數(shù)據(jù)
    self.axdict[index].plot(x, y) # 繪制最新的數(shù)據(jù)
    self.setPlotStyle(index) # 設(shè)置子圖樣式
    if min(x) < max(x):
      self.axdict[index].set_xlim(min(x), max(x)) # 根據(jù)X軸數(shù)據(jù)區(qū)間調(diào)整X軸范圍
    plt.draw()
    print("%s end" % sys._getframe().f_code.co_name)


def updatePlot(plot):
  """
  模擬收到實(shí)時數(shù)據(jù),更新曲線的操作
  :param plot: 曲線實(shí)例
  :return:
  """
  print("Thread: %s" % threading.current_thread().getName())
  count = 0
  global quit_flag
  print("quit_flag[%s]" % str(quit_flag))
  while True:
    if quit_flag:
      print("quit_flag[%s]" % str(quit_flag))
      break
    count += 1
    print("count#%d" % count)
    x = np.arange(0, 100, 1)
    y = np.random.normal(loc=1, scale=1, size=100) # 產(chǎn)生隨機(jī)數(shù),模擬變化的曲線
    index = randrange(4) # 隨機(jī)更新某一個子圖
    plot.updatePlot(index, x, y)
    sleep(random() * 3)


def main():
  p = Plot2_2() # 創(chuàng)建一個2X2畫板

  t = threading.Thread(target=updatePlot, args=(p,)) # 啟動一個線程更新曲線數(shù)據(jù)
  t.start()

  p.showPlot() # showPlot方法會阻塞當(dāng)前線程,直到窗口關(guān)閉
  print("plot close")
  global quit_flag
  quit_flag = True # 通知更新曲線數(shù)據(jù)的線程退出

  t.join()
  print("Thread: %s end" % threading.current_thread().getName())


if __name__ == '__main__':
  main()

關(guān)于使用matplotlib怎么實(shí)現(xiàn)一個數(shù)據(jù)實(shí)時刷新功能問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI