在循环内调用图形函数时,图形不是绘图

问题描述 投票:0回答:1

我希望通过从文件中读取数据来将图形显示为幻灯片。首先,我希望绘制第一组数据,然后是下一个,依此类推。我试过的是:

class MatplotlibWidget(QMainWindow):

    def __init__(self):
        ---
        self.playbutton.clicked.connect(self.drawGraph)
        self.pausebutton.clicked.connect(self.pauseGraph)

        ----      

   def drawGraph(self):
        f1 = open('TESTIP2.txt', 'r')        
        data = np.genfromtxt(f1)
        m = np.size(data, 0)
        n = np.size(data, 1)
        x = data[:, 0].reshape(m, 1)
        y = data[:, 1].reshape(m, 1)
        iters = m // 4
        current_iter=0
        self.plotGraph(x,y,iters,current_iter)

   def plotGraph(x,y,iters,current_iter):
        for i in range(iters):
           self.plotDraw(x[current_iter:current_iter+iters],y[current_iter:current_iter+iters])
           current_iter=current_iter+iters
           time.sleep(1)

   def plotDraw(x,y)       
        self.MplWidget.canvas.axes.clear()
        self.MplWidget.canvas.axes.plot(x,y)
        self.MplWidget.canvas.axes.legend(('cosinus', 'sinus'), loc='upper right')
        self.MplWidget.canvas.axes.set_title('Signal' )
        self.MplWidget.canvas.draw()

plotDraw函数在循环内部调用以显示每组数据,但它仅显示最后一组数据。有没有办法在特定时间间隔后显示第一个,第二个等等。

python matplotlib pyqt5
1个回答
1
投票

最简单的方法是使用QTimerPyQt5。这非常容易使用:指定一个应该在超时后触发的函数,并指定时间间隔。使用以下代码,我在PyQt5内的Matplotlib Widget中每秒绘制随机数据。

from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtCore import QTimer
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np


class M(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(100,100,640,480)
        self.Figure = Figure()
        self.Canvas = FigureCanvas(self.Figure)
        self.Canvas.setParent(self)
        self.Canvas.move(0,0)

        self.ax = self.Figure.add_subplot(111)
        self.plotItem, = self.ax.plot([], [])
        self.plot()

        # Create timer
        self.t = QTimer()
        self.t.timeout.connect(self.plot) # specify function 
        self.t.start(1000) # 1 s


    def plot(self):
        """plots random data and adjusts the x and y limits"""
        x = np.linspace(0, np.random.randn()*100)
        y = np.random.randn(50)

        self.plotItem.set_xdata(x)
        self.plotItem.set_ydata(y)
        self.ax.set_ylim([y.min()-1, y.max()+1])
        self.ax.set_xlim([x.min()-1, x.max()+1])
        self.Canvas.draw() # update plot


if __name__ == '__main__':
    app = QApplication([])
    m = M()
    m.show()
    app.exec_()

上面的代码为您提供:

Changing x and y data every second using QTimer object

你可以使用一个按钮触发self.t.stop()来停止更新/循环,如果你想继续,你可以再次self.t.start(your_interval)

© www.soinside.com 2019 - 2024. All rights reserved.