|
| 1 | +import sys |
| 2 | +from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton |
| 3 | +from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas |
| 4 | +from matplotlib.figure import Figure |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +class MainWindow(QMainWindow): |
| 8 | + def __init__(self): |
| 9 | + super().__init__() |
| 10 | + self.setWindowTitle("Matplotlib with PyQt") |
| 11 | + self.setGeometry(100, 100, 800, 600) |
| 12 | + |
| 13 | + # Create a central widget |
| 14 | + central_widget = QWidget() |
| 15 | + self.setCentralWidget(central_widget) |
| 16 | + |
| 17 | + # Create a layout for the central widget |
| 18 | + layout = QVBoxLayout() |
| 19 | + central_widget.setLayout(layout) |
| 20 | + |
| 21 | + # Create a Matplotlib figure |
| 22 | + self.figure = Figure(figsize=(5, 4), dpi=100) |
| 23 | + self.canvas = FigureCanvas(self.figure) |
| 24 | + layout.addWidget(self.canvas) |
| 25 | + |
| 26 | + # Create a button to update the plot |
| 27 | + button = QPushButton("Update Plot") |
| 28 | + button.clicked.connect(self.update_plot) |
| 29 | + layout.addWidget(button) |
| 30 | + |
| 31 | + # Initial plot |
| 32 | + self.update_plot() |
| 33 | + |
| 34 | + def update_plot(self): |
| 35 | + # Clear the previous plot |
| 36 | + self.figure.clear() |
| 37 | + |
| 38 | + # Generate data |
| 39 | + x = np.linspace(0, 10, 100) |
| 40 | + y = np.sin(x) |
| 41 | + |
| 42 | + # Plot data |
| 43 | + ax = self.figure.add_subplot(111) |
| 44 | + ax.plot(x, y) |
| 45 | + ax.set_xlabel('X-axis') |
| 46 | + ax.set_ylabel('Y-axis') |
| 47 | + ax.set_title('Matplotlib Plot') |
| 48 | + |
| 49 | + # Update canvas |
| 50 | + self.canvas.draw() |
| 51 | + |
| 52 | +if __name__ == '__main__': |
| 53 | + app = QApplication(sys.argv) |
| 54 | + window = MainWindow() |
| 55 | + window.show() |
| 56 | + sys.exit(app.exec_()) |
0 commit comments