在 PyQt4 中嵌入 Matplotlib:综合指南
通过集成 Matplotlib,可以在 PyQt4 用户界面中无缝创建交互式数据可视化。虽然查找嵌入 Matplotlib 的示例可能具有挑战性,但掌握该过程非常简单。
如何在 PyQt4 中嵌入 Matplotlib
要将 Matplotlib 嵌入 PyQt4,请按照以下步骤操作:
示例代码:
这里有一个简单的代码示例来说明该过程:
<code class="python">import sys from PyQt4 import QtGui from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure import random class Window(QtGui.QDialog): def __init__(self, parent=None): super(Window, self).__init__(parent) # a figure instance to plot on self.figure = Figure() # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) # this is the Navigation widget # it takes the Canvas widget and a parent self.toolbar = NavigationToolbar(self.canvas, self) # Just some button connected to `plot` method self.button = QtGui.QPushButton('Plot') self.button.clicked.connect(self.plot) # set the layout layout = QtGui.QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) layout.addWidget(self.button) self.setLayout(layout) def plot(self): ''' plot some random stuff ''' # random data data = [random.random() for i in range(10)] # create an axis ax = self.figure.add_subplot(111) # discards the old graph ax.clear() # plot data ax.plot(data, '*-') # refresh canvas self.canvas.draw() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) main = Window() main.show() sys.exit(app.exec_())</code>
以上是如何将 Matplotlib 可视化集成到 PyQt4 应用程序中?的详细内容。更多信息请关注PHP中文网其他相关文章!