[Python] Clear and repopulate Matplotlib in PyQt5?

Discussão em 'Python' iniciado por Stack, Julho 11, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to update a graph with new data after a refresh button is pressed. To achieve this, I would like to delete or clear the existing graph and then recreate it. I am using matplotlib within my PyQt5 GUI window. More specifically, the parent of my matplotlib graph is a PyQt5 GroupBox.

    This is the code that I use to construct the plot:

    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)


    This is the code that I use to apply the data to the plot:

    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()


    I have tried several different approaches involving clear(), clf(), and cla(). In addition to other various approaches, I have not been able to clear or delete the existing plot.

    What I would like is to clear my existing plot and then just call my function plot() again. How is this possible?

    Continue reading...

Compartilhe esta Página