写一个示列,使用pyqt5和matplotlib,画一个散点图,画出来的散点再用线连起来,散点的x轴下标是对应的当前时间,格式是小时:分:秒,随着时间散点不断增加,但是画板上的被线连起来的散点不能超过30个
时间: 2024-03-21 15:43:22 浏览: 51
好的,下面是示例代码:
```python
import sys
import random
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout
from PyQt5.QtCore import QTimer
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class ScatterPlot(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Scatter Plot')
self.fig = Figure()
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvas(self.fig)
self.setLayout(QVBoxLayout())
self.layout().addWidget(self.canvas)
self.x = []
self.y = []
self.lines = []
self.timer = QTimer(self)
self.timer.timeout.connect(self.update_plot)
self.timer.start(1000)
def update_plot(self):
self.x.append(len(self.x))
self.y.append(random.randint(0, 100))
if len(self.x) > 30:
self.x.pop(0)
self.y.pop(0)
for line in self.lines:
line.remove()
self.lines.pop(0)
self.ax.clear()
self.ax.scatter(self.x, self.y)
line, = self.ax.plot(self.x, self.y, 'r-')
self.lines.append(line)
self.ax.set_xlim(0, len(self.x)+1)
self.ax.set_xticks(range(len(self.x)))
self.ax.set_xticklabels([f'{i:02d}:00:00' for i in range(len(self.x))])
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
plot = ScatterPlot()
plot.setGeometry(100, 100, 800, 600)
plot.show()
sys.exit(app.exec_())
```
运行代码后,会弹出一个窗口,每秒钟会在散点图中增加一个点,并用线将所有点连起来,超过30个点后会删除最早的点和对应的线。散点的x轴下标表示当前时间,格式为小时:分:秒,随着时间不断增加。
阅读全文