Search code examples
pythonmatplotlibpyqt4matplotlib-widget

How to clear a plot with a pushButton in PyQt?


I have created a little GUI in PyQt using QT Designer. I have one button."Clear" button must clear this plot(My clear button calls pushButton). I try to write some code but it don't run. How can I create this clear button? Thank you.

import sys
from PyQt4 import QtCore, QtGui, uic


form_class = uic.loadUiType("gugus.ui")[0]  # Load the UI


class MyWindowClass(QtGui.QMainWindow, form_class):

def __init__(self, parent=None):

    QtGui.QMainWindow.__init__(self, parent)
    self.setupUi(self)

    self.pushButton.clicked.connect(self.btn_pgb)
    self.matplotlibwidget.axes.plot([0, 1, 1.5, 3], [50, 1, 2, 0])

def btn_pgb(self):  

    # Her I should clear my plot, but don`t know how `enter code here`
    self.progressBar.setValue(69)


app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass()
myWindow.show()
app.exec_()

Solution

  • To clear the axes, use axes.clear(). To clear the complete figure, use axes.figure.clear().

    In your case this would be

    self.matplotlibwidget.axes.clear()
    

    or

    self.matplotlibwidget.axes.figure.clear()
    

    After that you would need to redraw the canvas.

    self.matplotlibwidget.axes.figure.canvas.draw_idle()