问题描述
几年前,我已经尝试在 pyqt5 gui 中嵌入实时 matplotlib 图.实时图显示了从传感器捕获的实时数据流、一些过程……我得到了它的工作,您可以在此处阅读相关帖子:
2.第二个例子
我在这里找到了另一个实时 matplotlib 图示例:
这没什么大不了的,但我只是想知道为什么.百家乐凯发k8的解决方案第二种情况(使用funcanimation)更快,因为它使用blitting",这可以避免重绘帧之间不会改变的东西.
matplotlib 网站上提供的嵌入 qt 的示例没有考虑速度,因此性能较差.您会注意到它在每次迭代时调用 ax.clear() 和 ax.plot(),导致每次都重新绘制整个画布.如果要使用与 funcanimation 中的代码相同的代码(也就是说,创建一个 axes 和一个艺术家,并更新艺术家中的数据,而不是每次都创建一个新艺术家)你应该得到非常接近我相信的相同性能.
some years ago, i already experimented with embedding live matplotlib plots in a pyqt5 gui. live plots show a data-stream real-time, captured from a sensor, some process, ... i got that working, and you can read the related posts here:
matplotlib animation inside your own gui
how do i plot in real-time in a while loop using matplotlib?
now i need to do the same thing again. i remember my previous approach worked, but couldn't keep up with fast datastreams. i found a couple of example codes on the internet, that i'd like to present to you. one of them is clearly faster than the other, but i don't know why. i'd like to gain more insights. i believe a deeper understanding will enable me to keep my interactions with pyqt5 and matplotlib efficient.
1. first example
this example is based on this article:
http://www.51sjk.com/upload/articles/1/0/340/340381_20221223101758027.html
the article is from the official matplotlib website, and explains how to embed a matplotlib figure in a pyqt5 window.i did a few minor adjustments to the example code, but the basics are still the same. please copy-paste the code below to a python file and run it:
##################################################################################### # # # plot a live graph in a pyqt window # # example 1 # # ------------------------------------ # # this code is inspired on: # # http://www.51sjk.com/upload/articles/1/0/340/340381_20221223101758027.html # # # ##################################################################################### from __future__ import annotations from typing import * import sys import os from matplotlib.backends.qt_compat import qtcore, qtwidgets # from pyqt5 import qtwidgets, qtcore from matplotlib.backends.backend_qt5agg import figurecanvas # from matplotlib.backends.backend_qt5agg import figurecanvasqtagg as figurecanvas import matplotlib as mpl import numpy as np class applicationwindow(qtwidgets.qmainwindow): ''' the pyqt5 main window. ''' def __init__(self): super().__init__() # 1. window settings self.setgeometry(300, 300, 800, 400) self.setwindowtitle("matplotlib live plot in pyqt - example 1") self.frm = qtwidgets.qframe(self) self.frm.setstylesheet("qwidget { background-color: #eeeeec; }") self.lyt = qtwidgets.qvboxlayout() self.frm.setlayout(self.lyt) self.setcentralwidget(self.frm) # 2. place the matplotlib figure self.myfig = myfigurecanvas(x_len=200, y_range=[0, 100], interval=20) self.lyt.addwidget(self.myfig) # 3. show self.show() return class myfigurecanvas(figurecanvas): ''' this is the figurecanvas in which the live plot is drawn. ''' def __init__(self, x_len:int, y_range:list, interval:int) -> none: ''' :param x_len: the nr of data points shown in one plot. :param y_range: range on y-axis. :param interval: get a new datapoint every .. milliseconds. ''' super().__init__(mpl.figure.figure()) # range settings self._x_len_ = x_len self._y_range_ = y_range # store two lists _x_ and _y_ self._x_ = list(range(0, x_len)) self._y_ = [0] * x_len # store a figure ax self._ax_ = self.figure.subplots() # initiate the timer self._timer_ = self.new_timer(interval, [(self._update_canvas_, (), {})]) self._timer_.start() return def _update_canvas_(self) -> none: ''' this function gets called regularly by the timer. ''' self._y_.append(round(get_next_datapoint(), 2)) # add new datapoint self._y_ = self._y_[-self._x_len_:] # truncate list _y_ self._ax_.clear() # clear ax self._ax_.plot(self._x_, self._y_) # plot y(x) self._ax_.set_ylim(ymin=self._y_range_[0], ymax=self._y_range_[1]) self.draw() return # data source # ------------ n = np.linspace(0, 499, 500) d = 50 25 * (np.sin(n / 8.3)) 10 * (np.sin(n / 7.5)) - 5 * (np.sin(n / 1.5)) i = 0 def get_next_datapoint(): global i i = 1 if i > 499: i = 0 return d[i] if __name__ == "__main__": qapp = qtwidgets.qapplication(sys.argv) app = applicationwindow() qapp.exec_()
you should see the following window:
2. second example
i found another example of live matplotlib graphs here:
http://www.51sjk.com/upload/articles/1/0/340/340381_20221223101758965.jpg
however, the author doesn't use pyqt5 to embed his live plot. therefore, i've modified the code a bit, to get the plot in a pyqt5 window:##################################################################################### # # # plot a live graph in a pyqt window # # example 2 # # ------------------------------------ # # this code is inspired on: # # http://www.51sjk.com/upload/articles/1/0/340/340381_20221223101758965.jpg # # # ##################################################################################### from __future__ import annotations from typing import * import sys import os from matplotlib.backends.qt_compat import qtcore, qtwidgets # from pyqt5 import qtwidgets, qtcore from matplotlib.backends.backend_qt5agg import figurecanvas # from matplotlib.backends.backend_qt5agg import figurecanvasqtagg as figurecanvas import matplotlib as mpl import matplotlib.figure as mpl_fig import matplotlib.animation as anim import numpy as np class applicationwindow(qtwidgets.qmainwindow): ''' the pyqt5 main window. ''' def __init__(self): super().__init__() # 1. window settings self.setgeometry(300, 300, 800, 400) self.setwindowtitle("matplotlib live plot in pyqt - example 2") self.frm = qtwidgets.qframe(self) self.frm.setstylesheet("qwidget { background-color: #eeeeec; }") self.lyt = qtwidgets.qvboxlayout() self.frm.setlayout(self.lyt) self.setcentralwidget(self.frm) # 2. place the matplotlib figure self.myfig = myfigurecanvas(x_len=200, y_range=[0, 100], interval=20) self.lyt.addwidget(self.myfig) # 3. show self.show() return class myfigurecanvas(figurecanvas, anim.funcanimation): ''' this is the figurecanvas in which the live plot is drawn. ''' def __init__(self, x_len:int, y_range:list, interval:int) -> none: ''' :param x_len: the nr of data points shown in one plot. :param y_range: range on y-axis. :param interval: get a new datapoint every .. milliseconds. ''' figurecanvas.__init__(self, mpl_fig.figure()) # range settings self._x_len_ = x_len self._y_range_ = y_range # store two lists _x_ and _y_ x = list(range(0, x_len)) y = [0] * x_len # store a figure and ax self._ax_ = self.figure.subplots() self._ax_.set_ylim(ymin=self._y_range_[0], ymax=self._y_range_[1]) self._line_, = self._ax_.plot(x, y) # call superclass constructors anim.funcanimation.__init__(self, self.figure, self._update_canvas_, fargs=(y,), interval=interval, blit=true) return def _update_canvas_(self, i, y) -> none: ''' this function gets called regularly by the timer. ''' y.append(round(get_next_datapoint(), 2)) # add new datapoint y = y[-self._x_len_:] # truncate list _y_ self._line_.set_ydata(y) return self._line_, # data source # ------------ n = np.linspace(0, 499, 500) d = 50 25 * (np.sin(n / 8.3)) 10 * (np.sin(n / 7.5)) - 5 * (np.sin(n / 1.5)) i = 0 def get_next_datapoint(): global i i = 1 if i > 499: i = 0 return d[i] if __name__ == "__main__": qapp = qtwidgets.qapplication(sys.argv) app = applicationwindow() qapp.exec_()
the resulting live plot is exactly the same. however, if you start playing around with the interval parameter from the myfigurecanvas() constructor, you will notice that the first example won't be able to follow. the second example can go much faster.
3. questions
i've got a couple of questions i'd like to present to you:
the qtcore and qtwidgets classes can be imported like this:
from matplotlib.backends.qt_compat import qtcore, qtwidgets
or like this:
from pyqt5 import qtwidgets, qtcore
both work equally well. is there a reason to prefer one over the other?
the figurecanvas can be imported like this:
from matplotlib.backends.backend_qt5agg import figurecanvas
or like this: from matplotlib.backends.backend_qt5agg import figurecanvasqtagg as figurecanvas
but i already figured out why. the backend_qt5agg file seems to define figurecanvas as an alias for figurecanvasqtagg.
why exactly is the second example so much faster than the first one? honestly, it surprises me. the first example is based on a webpage from the official matplotlib website. i'd expect that one to be better.
do you have any suggestions to make the second example even faster?
4. edits
based on the webpage:
http://www.51sjk.com/upload/articles/1/0/340/340381_20221223101800950.html
i modified the first example to increase its speed. please have a look at the code:##################################################################################### # # # plot a live graph in a pyqt window # # example 1 (modified for extra speed) # # -------------------------------------- # # this code is inspired on: # # http://www.51sjk.com/upload/articles/1/0/340/340381_20221223101758027.html # # and on: # # http://www.51sjk.com/upload/articles/1/0/340/340381_20221223101800950.html # # # ##################################################################################### from __future__ import annotations from typing import * import sys import os from matplotlib.backends.qt_compat import qtcore, qtwidgets # from pyqt5 import qtwidgets, qtcore from matplotlib.backends.backend_qt5agg import figurecanvas # from matplotlib.backends.backend_qt5agg import figurecanvasqtagg as figurecanvas import matplotlib as mpl import numpy as np class applicationwindow(qtwidgets.qmainwindow): ''' the pyqt5 main window. ''' def __init__(self): super().__init__() # 1. window settings self.setgeometry(300, 300, 800, 400) self.setwindowtitle("matplotlib live plot in pyqt - example 1 (modified for extra speed)") self.frm = qtwidgets.qframe(self) self.frm.setstylesheet("qwidget { background-color: #eeeeec; }") self.lyt = qtwidgets.qvboxlayout() self.frm.setlayout(self.lyt) self.setcentralwidget(self.frm) # 2. place the matplotlib figure self.myfig = myfigurecanvas(x_len=200, y_range=[0, 100], interval=1) self.lyt.addwidget(self.myfig) # 3. show self.show() return class myfigurecanvas(figurecanvas): ''' this is the figurecanvas in which the live plot is drawn. ''' def __init__(self, x_len:int, y_range:list, interval:int) -> none: ''' :param x_len: the nr of data points shown in one plot. :param y_range: range on y-axis. :param interval: get a new datapoint every .. milliseconds. ''' super().__init__(mpl.figure.figure()) # range settings self._x_len_ = x_len self._y_range_ = y_range # store two lists _x_ and _y_ self._x_ = list(range(0, x_len)) self._y_ = [0] * x_len # store a figure ax self._ax_ = self.figure.subplots() self._ax_.set_ylim(ymin=self._y_range_[0], ymax=self._y_range_[1]) # added self._line_, = self._ax_.plot(self._x_, self._y_) # added self.draw() # added # initiate the timer self._timer_ = self.new_timer(interval, [(self._update_canvas_, (), {})]) self._timer_.start() return def _update_canvas_(self) -> none: ''' this function gets called regularly by the timer. ''' self._y_.append(round(get_next_datapoint(), 2)) # add new datapoint self._y_ = self._y_[-self._x_len_:] # truncate list y # previous code # -------------- # self._ax_.clear() # clear ax # self._ax_.plot(self._x_, self._y_) # plot y(x) # self._ax_.set_ylim(ymin=self._y_range_[0], ymax=self._y_range_[1]) # self.draw() # new code # --------- self._line_.set_ydata(self._y_) self._ax_.draw_artist(self._ax_.patch) self._ax_.draw_artist(self._line_) self.update() self.flush_events() return # data source # ------------ n = np.linspace(0, 499, 500) d = 50 25 * (np.sin(n / 8.3)) 10 * (np.sin(n / 7.5)) - 5 * (np.sin(n / 1.5)) i = 0 def get_next_datapoint(): global i i = 1 if i > 499: i = 0 return d[i] if __name__ == "__main__": qapp = qtwidgets.qapplication(sys.argv) app = applicationwindow() qapp.exec_()
the result is pretty amazing. the modifications make the first example definitely much faster! however, i don't know if this makes the first example equally fast now to the second example. they're certainly close to each other. anyone an idea who wins?
also, i noticed that one vertical line on the left, and one horizontal line on top is missing: it's not a big deal, but i just wonder why.
百家乐凯发k8的解决方案the second case (using funcanimation) is faster because it uses "blitting", which avoids redrawing things that do not change between frames.
the example provided on the matplotlib website for embedding in qt was not written with speed in mind, hence the poorer performance. you'll notice that it calls ax.clear() and ax.plot() at each iteration, causing the whole canvas to be redrawn everytime. if you were to use the same code as in the code with funcanimation (that is to say, create an axes and an artist, and update the data in the artist instead of creating a new artists every time) you should get pretty close to the same performance i believe.
;