【问题标题】:Clear and repopulate Matplotlib in PyQt5?在 PyQt5 中清除并重新填充 Matplotlib?
【发布时间】:2021-11-04 17:11:05
【问题描述】:

我想在按下刷新按钮后用新数据更新图表。为此,我想删除或清除现有图表,然后重新创建它。我在我的PyQt5 GUI 窗口中使用matplotlib。更具体地说,我的 matplotlib 图的父级是 PyQt5 GroupBox

这是我用来构建情节的代码:

def initEventGraph(self, parent, numDays=7): 
    self.canvas = FigureCanvas(plt.Figure(figsize=(6.31,4.75), dpi=80))
    self.canvas.setParent(parent)
    self.canvas.move(10,20)

    self.ax = self.canvas.figure.subplots()

    FigureCanvas.setSizePolicy(self,
            QSizePolicy.Expanding,
            QSizePolicy.Expanding)
    FigureCanvas.updateGeometry(self)

    self.plot(num_days=numDays)

这是我用来将数据应用于绘图的代码:

def plot(self,num_days):
    current_time = datetime.datetime.now()
    events = self.findXDayOldEvents(days=num_days, current_time=current_time) 
    sorted_events = self.sortEventList(events)

    for event_name, entries in sorted_events.items(): 
        x_axis = entries["Time"]
        y_axis = entries["Channel"]
        color = entries["Color"]
        self.ax.scatter(x_axis, y_axis,color=color, label=event_name)
        self.ax.tick_params(labelrotation=15)
    self.ax.legend()
    self.ax.set_ylabel("Channel")
    self.ax.grid()

我尝试了几种不同的方法,涉及clear()clf()cla()。除了其他各种方法之外,我一直无法清除或删除现有的情节。

我想要清除我现有的情节,然后再次调用我的函数plot()。这怎么可能?

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    您好,您的代码无法运行,我们需要 Minimal Reproducible Example ,至少我可以,除非这里有更好的人来处理它。尽管如此,我还是对你的问题很感兴趣,所以用谷歌搜索了一下,发现了很好的教程:https://www.pythonguis.com/tutorials/plotting-matplotlib/

    从那里我偷了一些代码来尝试重现一些关于 '在 PyQt5 中清除并重新填充 Matplotlib'。

    看看我的代码,清除后别忘了canvas.draw()

    
    import sys
    import random
    import matplotlib
    
    matplotlib.use('Qt5Agg')
    
    from PyQt5 import QtCore, QtWidgets
    
    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.figure import Figure
    
    
    
    def random_list(n , v):
            randomlist = []
            for i in range(0,n):
                add = random.randint(0,v)
                randomlist.append(add)
            print(randomlist)
            
            return randomlist   
    
    class MplCanvas(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)
            super(MplCanvas, self).__init__(fig)
    
    
    class MainWindow(QtWidgets.QMainWindow):
    
        def __init__(self, *args, **kwargs):
            
            self.deleted = ''
            
            super(MainWindow, self).__init__(*args, **kwargs)
    
    
            self.setGeometry(10,80,800,600)
            
            self.pushButton_1 = QtWidgets.QPushButton(self)
            self.pushButton_1.setGeometry(QtCore.QRect(600, 520, 150, 50))
            self.pushButton_1.setObjectName("pushButton_1")
            self.pushButton_1.setStyleSheet('background-color: red;')
            self.pushButton_1.setText('Re-Draw')
            
            self.pushButton_2 = QtWidgets.QPushButton(self)
            self.pushButton_2.setGeometry(QtCore.QRect(600, 450, 150, 50))
            self.pushButton_2.setObjectName("pushButton_2")
            self.pushButton_2.setStyleSheet('background-color: blue;')
            self.pushButton_2.setText('Clean_Cla')
            
            self.pushButton_3 = QtWidgets.QPushButton(self)
            self.pushButton_3.setGeometry(QtCore.QRect(400, 520, 150, 50))
            self.pushButton_3.setObjectName("pushButton_3")
            self.pushButton_3.setStyleSheet('background-color: yellow;')
            self.pushButton_3.setText('Rebuild')
            
            
            self.pushButton_1.clicked.connect(self.update_plot)
            
            self.pushButton_2.clicked.connect(self.clean_cla_plot)
            
            self.pushButton_3.clicked.connect(self.rebuild)
            
            self.canvas2 = MplCanvas(self, width=5, height=4, dpi=50)
            self.canvas2.setParent(self)
            self.canvas2.move(450,0)
            
            self.canvas3 = MplCanvas(self, width=5, height=4, dpi=50)
            self.canvas3.setParent(self)
            self.canvas3.move(450,200)
            
            self.canvas = MplCanvas(self, width=8, height=8, dpi=50)
            self.canvas.setParent(self)
            
            # self.setCentralWidget(self.canvas)
    
    
            self.xdata = random_list(20, 50)
            self.ydata = random_list(20, 50)
            self.update_plot()
    
            
            
            
            self.show()
            
            print('@@@@@@ : ',self.deleted, type(self.deleted))
    
    
        def update_plot(self):
            
            print('update', 'self.deleted : ', self.deleted)
            self.canvas.axes.cla()  # Clear the canvas.
            self.canvas.axes.scatter(random_list(20, 50), random_list(20, 50))
            # Trigger the canvas to update and redraw.
            self.canvas.draw()
            
            self.canvas2.axes.cla()  # Clear the canvas.
            self.canvas2.axes.scatter(random_list(20, 50), random_list(20, 50), c = 'red')
            # Trigger the canvas to update and redraw.
            self.canvas2.draw()
            self.canvas2.show()
            
            
            if self.deleted != 'yep' :
                self.canvas3.axes.cla()  # Clear the canvas.
                self.canvas3.axes.scatter(random_list(20, 50), random_list(20, 50), c = 'green')
                # Trigger the canvas to update and redraw.
                self.canvas3.draw()
                self.canvas3.show()
            
            
        def clean_cla_plot(self):
            
            print('clean')
            self.canvas.axes.cla()  # Clear the canvas.
            self.canvas2.axes.clear() 
            
            # Trigger the canvas to update and redraw.
            self.canvas.draw()
            self.canvas2.hide()   
            
            if self.deleted != 'yep':
                self.canvas3.deleteLater()
                self.deleted = 'yep'
                
        
        def rebuild(self):
            
            if self.deleted == 'yep' :
                # self.canvas3.cla()
                print(self.canvas3)
                self.canvas3 = MplCanvas(self, width=5, height=4, dpi=50)
                self.canvas3.setParent(self)
                self.canvas3.move(450,200)
                print(self.canvas3)
                self.deleted = 'nope' 
                print('rebbuild', 'self.deleted : ', self.deleted)
    
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    app.exec_()
    
    

    【讨论】:

      猜你喜欢
      • 2015-03-29
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 2023-02-02
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多