我想知道Matplotlib绘图如何在PyQT5桌面应用程序上工作。 我尝试了几种方法来绘制图形,但没有帮助。 我使用了打印功能,以便我至少可以知道该图已绘制。它按打印方式打印,但不显示图形。在这里需要一些帮助。下面是我的代码
'''
Created on Oct 8, 2018
@author: kjohn
'''
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog, QMessageBox, QMainWindow, QVBoxLayout
from PyQt5.QtGui import QIcon
import os
import csv
import matplotlib
from matplotlib import figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
class MatplotlibFigure(QWidget):
def __init__(self):
super().__init__()
self.figure = matplotlib.figure.Figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, self)
def plot(self):
self.figure.clf()
ax = self.figure.add_subplot(111)
x = [i for i in range(100)]
y = [i**0.5 for i in x]
ax.plot(x, y, 'g*-')
self.canvas.draw_idle()
print('PLOTTED')
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(1001, 651)
font = QtGui.QFont()
font.setFamily("Segoe UI")
Form.setFont(font)
Form.setMouseTracking(True)
Form.setWindowTitle("Data Analytical Tool Kit")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(440, 70, 121, 25))
self.pushButton.clicked.connect(self.inputfileselector)
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.pushButton.setFont(font)
self.pushButton.setMouseTracking(True)
self.pushButton.setObjectName("pushButton")
self.comboBox = QtWidgets.QComboBox(Form)
self.comboBox.setGeometry(QtCore.QRect(670, 70, 241, 30))
font = QtGui.QFont()
font.setFamily("Segoe UI")
self.comboBox.setFont(font)
self.comboBox.setMouseTracking(True)
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem('Site Classifier')
self.comboBox.addItem('Account Classifier')
self.comboBox.addItem('Meter Classifier')
self.comboBox.addItem('EMS - Audit Engine')
self.comboBox.addItem('Budget Forecaster')
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(20, 70, 411, 25))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setPointSize(10)
self.lineEdit.setFont(font)
self.lineEdit.setAutoFillBackground(True)
self.lineEdit.setInputMethodHints(QtCore.Qt.ImhHiddenText)
self.lineEdit.setText("")
self.lineEdit.setObjectName("lineEdit")
self.lineEdit.setReadOnly(True)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(21, 51, 91, 16))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(671, 52, 108, 16))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.pushButton_2 = QtWidgets.QPushButton(Form)
self.pushButton_2.setGeometry(QtCore.QRect(669, 161, 121, 31))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_2.clicked.connect(self.plot_data)
self.pushButton_3 = QtWidgets.QPushButton(Form)
self.pushButton_3.setGeometry(QtCore.QRect(792, 161, 121, 31))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.pushButton_3.setFont(font)
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_4 = QtWidgets.QPushButton(Form)
self.pushButton_4.setGeometry(QtCore.QRect(440, 117, 121, 25))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.pushButton_4.setFont(font)
self.pushButton_4.setMouseTracking(True)
self.pushButton_4.setObjectName("pushButton_4")
self.pushButton_4.clicked.connect(self.outputfolderselector)
self.lineEdit_2 = QtWidgets.QLineEdit(Form)
self.lineEdit_2.setGeometry(QtCore.QRect(20, 117, 411, 25))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setPointSize(10)
self.lineEdit_2.setReadOnly(True)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setAutoFillBackground(True)
self.lineEdit_2.setInputMethodHints(QtCore.Qt.ImhHiddenText)
self.lineEdit_2.setText("")
self.lineEdit_2.setObjectName("lineEdit_2")
self.label_3 = QtWidgets.QLabel(Form)
self.label_3.setGeometry(QtCore.QRect(21, 97, 121, 16))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.textEdit = QtWidgets.QTextEdit(Form)
self.textEdit.setGeometry(QtCore.QRect(20, 210, 411, 421))
self.textEdit.setObjectName("textEdit")
self.progressBar = QtWidgets.QProgressBar(Form)
self.progressBar.setGeometry(QtCore.QRect(670, 116, 275, 31))
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName("progressBar")
self.pushButton_5 = QtWidgets.QPushButton(Form)
self.pushButton_5.setGeometry(QtCore.QRect(440, 166, 121, 25))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.pushButton_5.setFont(font)
self.pushButton_5.setMouseTracking(True)
self.pushButton_5.setObjectName("pushButton_5")
self.pushButton_5.clicked.connect(self.resultfolderselector)
self.lineEdit_3 = QtWidgets.QLineEdit(Form)
self.lineEdit_3.setGeometry(QtCore.QRect(20, 166, 411, 25))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setPointSize(7)
font.setPointSize(10)
self.lineEdit_3.setReadOnly(True)
self.lineEdit_3.setFont(font)
self.lineEdit_3.setAutoFillBackground(True)
self.lineEdit_3.setInputMethodHints(QtCore.Qt.ImhHiddenText)
self.lineEdit_3.setText("")
self.lineEdit_3.setObjectName("lineEdit_3")
self.label_4 = QtWidgets.QLabel(Form)
self.label_4.setGeometry(QtCore.QRect(22, 146, 121, 16))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
self.figure = matplotlib.figure.Figure()
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, Form)
self.verticalLayoutWidget = QtWidgets.QWidget(Form)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(440, 210, 541, 421))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.verticalLayout.addWidget(self.canvas)
self.verticalLayout.addWidget(self.toolbar)
self.figure = MatplotlibFigure()
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "Browse File"))
self.label.setText(_translate("Form", "Input File Upload"))
self.label_2.setText(_translate("Form", "Select Classifier Type"))
self.pushButton_2.setText(_translate("Form", "Submit"))
self.pushButton_3.setText(_translate("Form", "Cancel"))
self.pushButton_4.setText(_translate("Form", "Select Folder"))
self.label_3.setText(_translate("Form", "Output Folder for Logs"))
self.pushButton_5.setText(_translate("Form", "Select Folder"))
self.label_4.setText(_translate("Form", "Result Folder"))
Form.setWindowIcon(QtGui.QIcon('icon.png'))
Form.setWindowTitle('Data Analysis Tool Kit')
Form.setGeometry(180,50,1001,651)
Form.setFixedSize(1001,651)
Form.setWindowFlags( QtCore.Qt.CustomizeWindowHint | QtCore.Qt.MSWindowsFixedSizeDialogHint |QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint )
def inputfileselector(self):
path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
filename = QtWidgets.QFileDialog.getOpenFileName(None, 'Select the Input File', path,'All Files(*.csv*)')
if filename is filename:
self.lineEdit.setText(str(filename))
else:
self.lineEdit.setText("No file was selected.")
QtWidgets.QMessageBox.critical(Form, "Alert", "No file was selected.", QtWidgets.QMessageBox.Close)
def outputfolderselector(self):
path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
startingDir = path
directory = QtWidgets.QFileDialog.getExistingDirectory(None, 'Open working directory', startingDir, QtWidgets.QFileDialog.ShowDirsOnly)
if directory:
self.lineEdit_2.setText(directory)
else:
self.lineEdit_2.setText('')
QtWidgets.QMessageBox.critical(Form, "Alert", "No folder selected.", QtWidgets.QMessageBox.Close)
def resultfolderselector(self):
path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
startingDir = path
directory = QtWidgets.QFileDialog.getExistingDirectory(None, 'Open working directory', startingDir, QtWidgets.QFileDialog.ShowDirsOnly)
if directory:
self.lineEdit_3.setText(directory)
else:
self.lineEdit_3.setText('')
QtWidgets.QMessageBox.critical(Form, "Alert", "No folder selected.", QtWidgets.QMessageBox.Close)
def plot_data(self):
self.figure.plot()
self.canvas.setParent(self)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
答案 0 :(得分:1)
首先,您为matlabplot创建了一个class MatplotlibFigure
,同时在class Ui_Form
中定义了matlab函数,这是一个错误。解决您的问题,
我们需要在class MatplotlibFigure
中定义两个函数,第一个函数initializewidget()
定义matlabplot的画布小部件和图框,并放置QGridLayout
并进行布置。然后,第二个函数plot()
绘制输入数据。
def initializewidget(self):
gridlayout = QGridLayout()
self.setLayout(gridlayout)
self.figure = plt.figure(figsize=(5,5))
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas,self)
gridlayout.addWidget(self.canvas,1,0,1,2)
gridlayout.addWidget(self.toolbar,0,0,1,2)
最后,应将Matlabplot小部件添加到主小部件布局中。
self.matplot = MatplotlibFigure()
self.verticalLayout.addWidget(self.matplot)
Matplotlib.pyplot
用于获取更好的图形,甚至绘图也可以使用不同的样式进行自定义。
import matplotlib.pyplot as plt
plt.style.use('ggplot')
当前工作屏幕
工作代码
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit,
QFileDialog, QMessageBox, QMainWindow, QVBoxLayout, QGridLayout
from PyQt5.QtGui import QIcon
import os
import csv
import matplotlib
from matplotlib import figure
import matplotlib.pyplot as plt
plt.style.use('ggplot')
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
class MatplotlibFigure(QWidget):
def __init__(self):
super().__init__()
self.initializewidget()
self.plot()
def initializewidget(self):
gridlayout = QGridLayout()
self.setLayout(gridlayout)
self.figure = plt.figure(figsize=(5,5))
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas,self)
gridlayout.addWidget(self.canvas,1,0,1,2)
gridlayout.addWidget(self.toolbar,0,0,1,2)
def plot(self):
ax = self.figure.add_subplot(111)
x = [i for i in range(100)]
y = [1*i for i in x]
ax.plot(x, y, 'g*-')
self.canvas.draw()
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(1001, 651)
font = QtGui.QFont()
font.setFamily("Segoe UI")
Form.setFont(font)
Form.setMouseTracking(True)
Form.setWindowTitle("Data Analytical Tool Kit")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(440, 70, 121, 25))
self.pushButton.clicked.connect(self.inputfileselector)
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.pushButton.setFont(font)
self.pushButton.setMouseTracking(True)
self.pushButton.setObjectName("pushButton")
self.comboBox = QtWidgets.QComboBox(Form)
self.comboBox.setGeometry(QtCore.QRect(670, 70, 241, 30))
font = QtGui.QFont()
font.setFamily("Segoe UI")
self.comboBox.setFont(font)
self.comboBox.setMouseTracking(True)
self.comboBox.setObjectName("comboBox")
self.comboBox.addItem('Site Classifier')
self.comboBox.addItem('Account Classifier')
self.comboBox.addItem('Meter Classifier')
self.comboBox.addItem('EMS - Audit Engine')
self.comboBox.addItem('Budget Forecaster')
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(20, 70, 411, 25))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setPointSize(10)
self.lineEdit.setFont(font)
self.lineEdit.setAutoFillBackground(True)
self.lineEdit.setInputMethodHints(QtCore.Qt.ImhHiddenText)
self.lineEdit.setText("")
self.lineEdit.setObjectName("lineEdit")
self.lineEdit.setReadOnly(True)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(21, 51, 91, 16))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(671, 52, 108, 16))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.pushButton_2 = QtWidgets.QPushButton(Form)
self.pushButton_2.setGeometry(QtCore.QRect(669, 161, 121, 31))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_2.clicked.connect(self.plot_data)
self.pushButton_3 = QtWidgets.QPushButton(Form)
self.pushButton_3.setGeometry(QtCore.QRect(792, 161, 121, 31))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.pushButton_3.setFont(font)
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_4 = QtWidgets.QPushButton(Form)
self.pushButton_4.setGeometry(QtCore.QRect(440, 117, 121, 25))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.pushButton_4.setFont(font)
self.pushButton_4.setMouseTracking(True)
self.pushButton_4.setObjectName("pushButton_4")
self.pushButton_4.clicked.connect(self.outputfolderselector)
self.lineEdit_2 = QtWidgets.QLineEdit(Form)
self.lineEdit_2.setGeometry(QtCore.QRect(20, 117, 411, 25))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setPointSize(10)
self.lineEdit_2.setReadOnly(True)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setAutoFillBackground(True)
self.lineEdit_2.setInputMethodHints(QtCore.Qt.ImhHiddenText)
self.lineEdit_2.setText("")
self.lineEdit_2.setObjectName("lineEdit_2")
self.label_3 = QtWidgets.QLabel(Form)
self.label_3.setGeometry(QtCore.QRect(21, 97, 121, 16))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.textEdit = QtWidgets.QTextEdit(Form)
self.textEdit.setGeometry(QtCore.QRect(20, 210, 411, 421))
self.textEdit.setObjectName("textEdit")
self.progressBar = QtWidgets.QProgressBar(Form)
self.progressBar.setGeometry(QtCore.QRect(670, 116, 275, 31))
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName("progressBar")
self.pushButton_5 = QtWidgets.QPushButton(Form)
self.pushButton_5.setGeometry(QtCore.QRect(440, 166, 121, 25))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.pushButton_5.setFont(font)
self.pushButton_5.setMouseTracking(True)
self.pushButton_5.setObjectName("pushButton_5")
self.pushButton_5.clicked.connect(self.resultfolderselector)
self.lineEdit_3 = QtWidgets.QLineEdit(Form)
self.lineEdit_3.setGeometry(QtCore.QRect(20, 166, 411, 25))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setPointSize(7)
font.setPointSize(10)
self.lineEdit_3.setReadOnly(True)
self.lineEdit_3.setFont(font)
self.lineEdit_3.setAutoFillBackground(True)
self.lineEdit_3.setInputMethodHints(QtCore.Qt.ImhHiddenText)
self.lineEdit_3.setText("")
self.lineEdit_3.setObjectName("lineEdit_3")
self.label_4 = QtWidgets.QLabel(Form)
self.label_4.setGeometry(QtCore.QRect(22, 146, 121, 16))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
self.matplot = MatplotlibFigure()
self.verticalLayoutWidget = QtWidgets.QWidget(Form)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(440, 210, 541, 421))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
# self.verticalLayout.addWidget(self.matplot) # comment this line
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "Browse File"))
self.label.setText(_translate("Form", "Input File Upload"))
self.label_2.setText(_translate("Form", "Select Classifier Type"))
self.pushButton_2.setText(_translate("Form", "Submit"))
self.pushButton_3.setText(_translate("Form", "Cancel"))
self.pushButton_4.setText(_translate("Form", "Select Folder"))
self.label_3.setText(_translate("Form", "Output Folder for Logs"))
self.pushButton_5.setText(_translate("Form", "Select Folder"))
self.label_4.setText(_translate("Form", "Result Folder"))
Form.setWindowIcon(QtGui.QIcon('icon.png'))
Form.setWindowTitle('Data Analysis Tool Kit')
Form.setGeometry(180,50,1001,651)
Form.setFixedSize(1001,651)
Form.setWindowFlags( QtCore.Qt.CustomizeWindowHint |
QtCore.Qt.MSWindowsFixedSizeDialogHint |QtCore.Qt.WindowCloseButtonHint |
QtCore.Qt.WindowMinimizeButtonHint )
def inputfileselector(self):
path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
filename = QtWidgets.QFileDialog.getOpenFileName(None, 'Select the Input
File', path,'All Files(*.csv*)')
if filename is filename:
self.lineEdit.setText(str(filename))
else:
self.lineEdit.setText("No file was selected.")
QtWidgets.QMessageBox.critical(Form, "Alert", "No file was selected.",
QtWidgets.QMessageBox.Close)
def outputfolderselector(self):
path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
startingDir = path
directory = QtWidgets.QFileDialog.getExistingDirectory(None, 'Open working
directory', startingDir, QtWidgets.QFileDialog.ShowDirsOnly)
if directory:
self.lineEdit_2.setText(directory)
else:
self.lineEdit_2.setText('')
QtWidgets.QMessageBox.critical(Form, "Alert", "No folder selected.",
QtWidgets.QMessageBox.Close)
def resultfolderselector(self):
path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
startingDir = path
directory = QtWidgets.QFileDialog.getExistingDirectory(None, 'Open working
directory', startingDir, QtWidgets.QFileDialog.ShowDirsOnly)
if directory:
self.lineEdit_3.setText(directory)
else:
self.lineEdit_3.setText('')
QtWidgets.QMessageBox.critical(Form, "Alert", "No folder selected.",
QtWidgets.QMessageBox.Close)
def plot_data(self):
# self.figure.plot() # comment this line
# self.canvas.setParent(self) # comment this line
self.verticalLayout.addWidget(self.matplot) # <--- Add this line
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())