通过使用Matplotlib提供的“ Qt5Agg”后端,我将实时图形嵌入到PyQt5 GUI中。这是定义GUI和实时图的工作的代码。
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import random
import collections
import time
from PyQt5 import QtWidgets
class LiveGraphCanvas(FigureCanvas):
def __init__(self, parent=None, height=5, width=4, dpi=100):
fig = Figure(figsize=(height, width), dpi=dpi)
fig.set_tight_layout(True)
fig.patch.set_alpha(0.0)
self.axes = fig.add_subplot(111)
self.axes.set_xlabel("Data Points")
self.axes.set_ylabel("Trim width (um)")
self.axes.grid(True)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
# Function which will later be defined by the child-class
def compute_initial_figure(self):
pass
class LiveGraphWidget(LiveGraphCanvas):
def __init__(self, max_points, *args, **kwargs):
LiveGraphCanvas.__init__(self, *args, **kwargs)
self.data_length = max_points
self.data_points = collections.deque([0 for i in range(self.data_length)], maxlen=self.data_length)
def compute_initial_figure(self):
self.axes.plot([i for i in range(0, self.data_length)], [random.randint(1000, 6000) for i in range(0, self.data_length)], 'r')
def update_figure(self, data_point):
start_time = time.time()
self.data_points.append(data_point)
self.axes.cla()
self.axes.plot(self.data_points, 'r')
self.axes.set_xlabel("Data Points")
self.axes.set_ylabel("Trim width (um)")
self.axes.grid(True)
self.draw()
print ("Plot Update Time (ms): ", (time.time() - start_time)*1000)
然后创建LiveGraphWidget类的对象,并将其添加到主类的QVBoxLayout中。我想要在图形后面使用透明的Canvas,所以在LiveGraphCanvas类中将Alpha透明度设置为0。在Windows 10上,该图形会根据设置的alpha值正确显示,如下所示:
但是,在Ubuntu 18.04上,alpha参数不起作用,并且图形后面出现了难看的白色背景:
(请忽略两个屏幕截图之间的颜色和形状的差异,因为两者都是使用不同的软件拍摄的)
透明性无法正常工作的原因可能是什么?是由于Ubuntu的内部GUI限制还是Matplotlib不适用于该平台?