Python中matplotlib做的散点图放到主程序的Uii子界面上
时间: 2023-02-23 14:09:38 浏览: 93
如果你想在你的主程序的 UI 界面上显示 matplotlib 生成的散点图,你可以使用 PyQt5 库来实现这个功能。
下面是一个简单的例子:
```
import sys
import random
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
class MyMplCanvas(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):
x = [random.random() for i in range(25)]
y = [random.random() for i in range(25)]
self.axes.scatter(x, y)
class MyStaticMplCanvas(MyMplCanvas):
def __init__(self, *args, **kwargs):
MyMplCanvas.__init__(self, *args, **kwargs)
class ApplicationWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setAttribute(Qt.WA_DeleteOnClose)
self.setWindowTitle("application main window")
self.main_widget = QWidget(self)
self.layout = QVBoxLayout(self.main_widget)
self.sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)
self.layout.addWidget(self.sc)
self.main_widget.setFocus()
self.setCentralWidget(self.main_widget)
qApp = QApplication(sys.argv)
aw = ApplicationWindow()
aw.show()
sys.exit(qApp.exec_())
```
这个代码中,我们创建了一个继承自 FigureCanvas 的类,这个类实现了画散点图的功能。然后,我们在 ApplicationWindow 类中实例化了这个类,
阅读全文