python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy, QPushButton
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import random
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = '示例图像'
self.initUI()
self.m.plot() #调用PlotCanvas的函数画图
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(100, 100, 900, 400)
m = PlotCanvas(self, width=7, height=4)
m.move(0,0)
self.m = m
button = QPushButton('PyQt5 button', self)
button.setToolTip('This s an example button')
button.move(700,0)
button.resize(140,100)
self.show()
class PlotCanvas(FigureCanvas):
def __init__(self, parent=None, width=7, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi) #matplotlab的Figure类
self.axes = fig.add_subplot(111)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
def plot(self):
data = [random.random() for i in range(25)]
#ax = self.figure.clear()
#ax = self.figure.add_subplot(111)
ax = self.figure.axes[0] #获取原有的第一个axes
ax.plot(data, 'r-') #画图折线图,红色----
ax.set_title('PyQt Matplotlib Example')
self.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
添加一个继承自FigureCanvas的PlotCanvas类。
PlotCanvas类放置在PyQt窗口面板中。
在PlotCanvas类中调用matplotlab的Figure类,再通过获取axes,通过axes画图。