pyqt在canvas上matplotlib画图代码
时间: 2023-02-09 21:59:41 浏览: 197
下面是一个示例代码,使用 PyQt5 和 Matplotlib 在 canvas 上画图:
```
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy
from PyQt5.QtCore import Qt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class MyCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.plot()
def plot(self):
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = x ** 2
self.axes.plot(x, y)
class MyApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt5 & Matplotlib")
self.setGeometry(300, 300, 600, 400)
self.MyCanvas = MyCanvas(self)
self.setCentralWidget(self.MyCanvas)
app = QApplication(sys.argv)
w = MyApp()
w.show()
sys.exit(app.exec_())
```
这段代码中,我们首先定义了一个 MyCanvas 类,继承自 FigureCanvas。在 MyCanvas 的 __init__ 方法中,我们创建了一个 Figure 对象,并在其中添加了一个子图,然后调用父类构造函数。在 plot 方法中,我们使用 numpy 生成了一组数据,并绘制了曲线图。
接着定义了一个 MyApp 类继承自 QMainWindow,在其中我们创建了一个 MyCanvas 对象,并将其设为中央窗口部件,最后在运行时加载这个应用
阅读全文
相关推荐

















