Update an embedded matplotlib plot in a pyqt5 gui with toolbar










0















In this post I asked how to embed a matplotlib plot in a pyqt5 gui which is working fine now. Now I have a further problem that I couldn't solve until now: how can I update the figure?



I tried to update the canvas by calling



self.plotWidget = FigureCanvas(fig)


every time with a new "fig" object but nothing happened. So I tried to add it to the layout



self.lay.addWidget(self.plotWidget)


but this adds another subplot to the widget. I guess that I have to clear the previous plot before updating but I don't know how to do it.



What is the correct strategy to replot using the update method?



Thanks!



# -*- coding: utf-8 -*-

import sys
import numpy as np

from PyQt5 import QtCore, QtWidgets, uic

import matplotlib
matplotlib.use('QT5Agg')

import matplotlib.pylab as plt

from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
from matplotlib.backends.backend_qt5agg import FigureCanvas, NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

class MyWindow(QMainWindow):

def __init__(self):

super(MyWindow, self).__init__()
uic.loadUi('test.ui', self)

# test data
data = np.array([0.7,0.7,0.7,0.8,0.9,0.9,1.5,1.5,1.5,1.5])
fig, ax1 = plt.subplots()
bins = np.arange(0.6, 1.62, 0.02)
n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)

# plot
self.plotWidget = FigureCanvas(fig)
self.lay = QtWidgets.QVBoxLayout(self.content_plot)
self.lay.setContentsMargins(0, 0, 0, 0)
self.lay.addWidget(self.plotWidget)

# add toolbar
self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(self.plotWidget, self))

# button event
self.pushButton.clicked.connect(self.update)

# show window
self.show()

#########################################

def update(self):

data = np.array([0.1,0.1,0.1,0.1,0.3,0.3,1.7,1.7,1.7,1.7])
fig, ax1 = plt.subplots()
bins = np.arange(0.6, 1.62, 0.02)
n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)

# show plot in canvas
self.plotWidget = FigureCanvas(fig)
self.toolbarWidget = NavigationToolbar(self.plotWidget, self)


if __name__ == '__main__':

app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
sys.exit(app.exec_())









share|improve this question


























    0















    In this post I asked how to embed a matplotlib plot in a pyqt5 gui which is working fine now. Now I have a further problem that I couldn't solve until now: how can I update the figure?



    I tried to update the canvas by calling



    self.plotWidget = FigureCanvas(fig)


    every time with a new "fig" object but nothing happened. So I tried to add it to the layout



    self.lay.addWidget(self.plotWidget)


    but this adds another subplot to the widget. I guess that I have to clear the previous plot before updating but I don't know how to do it.



    What is the correct strategy to replot using the update method?



    Thanks!



    # -*- coding: utf-8 -*-

    import sys
    import numpy as np

    from PyQt5 import QtCore, QtWidgets, uic

    import matplotlib
    matplotlib.use('QT5Agg')

    import matplotlib.pylab as plt

    from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
    from matplotlib.backends.backend_qt5agg import FigureCanvas, NavigationToolbar2QT as NavigationToolbar
    from matplotlib.figure import Figure

    class MyWindow(QMainWindow):

    def __init__(self):

    super(MyWindow, self).__init__()
    uic.loadUi('test.ui', self)

    # test data
    data = np.array([0.7,0.7,0.7,0.8,0.9,0.9,1.5,1.5,1.5,1.5])
    fig, ax1 = plt.subplots()
    bins = np.arange(0.6, 1.62, 0.02)
    n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)

    # plot
    self.plotWidget = FigureCanvas(fig)
    self.lay = QtWidgets.QVBoxLayout(self.content_plot)
    self.lay.setContentsMargins(0, 0, 0, 0)
    self.lay.addWidget(self.plotWidget)

    # add toolbar
    self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(self.plotWidget, self))

    # button event
    self.pushButton.clicked.connect(self.update)

    # show window
    self.show()

    #########################################

    def update(self):

    data = np.array([0.1,0.1,0.1,0.1,0.3,0.3,1.7,1.7,1.7,1.7])
    fig, ax1 = plt.subplots()
    bins = np.arange(0.6, 1.62, 0.02)
    n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)

    # show plot in canvas
    self.plotWidget = FigureCanvas(fig)
    self.toolbarWidget = NavigationToolbar(self.plotWidget, self)


    if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    window = MyWindow()
    sys.exit(app.exec_())









    share|improve this question
























      0












      0








      0








      In this post I asked how to embed a matplotlib plot in a pyqt5 gui which is working fine now. Now I have a further problem that I couldn't solve until now: how can I update the figure?



      I tried to update the canvas by calling



      self.plotWidget = FigureCanvas(fig)


      every time with a new "fig" object but nothing happened. So I tried to add it to the layout



      self.lay.addWidget(self.plotWidget)


      but this adds another subplot to the widget. I guess that I have to clear the previous plot before updating but I don't know how to do it.



      What is the correct strategy to replot using the update method?



      Thanks!



      # -*- coding: utf-8 -*-

      import sys
      import numpy as np

      from PyQt5 import QtCore, QtWidgets, uic

      import matplotlib
      matplotlib.use('QT5Agg')

      import matplotlib.pylab as plt

      from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
      from matplotlib.backends.backend_qt5agg import FigureCanvas, NavigationToolbar2QT as NavigationToolbar
      from matplotlib.figure import Figure

      class MyWindow(QMainWindow):

      def __init__(self):

      super(MyWindow, self).__init__()
      uic.loadUi('test.ui', self)

      # test data
      data = np.array([0.7,0.7,0.7,0.8,0.9,0.9,1.5,1.5,1.5,1.5])
      fig, ax1 = plt.subplots()
      bins = np.arange(0.6, 1.62, 0.02)
      n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)

      # plot
      self.plotWidget = FigureCanvas(fig)
      self.lay = QtWidgets.QVBoxLayout(self.content_plot)
      self.lay.setContentsMargins(0, 0, 0, 0)
      self.lay.addWidget(self.plotWidget)

      # add toolbar
      self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(self.plotWidget, self))

      # button event
      self.pushButton.clicked.connect(self.update)

      # show window
      self.show()

      #########################################

      def update(self):

      data = np.array([0.1,0.1,0.1,0.1,0.3,0.3,1.7,1.7,1.7,1.7])
      fig, ax1 = plt.subplots()
      bins = np.arange(0.6, 1.62, 0.02)
      n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)

      # show plot in canvas
      self.plotWidget = FigureCanvas(fig)
      self.toolbarWidget = NavigationToolbar(self.plotWidget, self)


      if __name__ == '__main__':

      app = QtWidgets.QApplication(sys.argv)
      window = MyWindow()
      sys.exit(app.exec_())









      share|improve this question














      In this post I asked how to embed a matplotlib plot in a pyqt5 gui which is working fine now. Now I have a further problem that I couldn't solve until now: how can I update the figure?



      I tried to update the canvas by calling



      self.plotWidget = FigureCanvas(fig)


      every time with a new "fig" object but nothing happened. So I tried to add it to the layout



      self.lay.addWidget(self.plotWidget)


      but this adds another subplot to the widget. I guess that I have to clear the previous plot before updating but I don't know how to do it.



      What is the correct strategy to replot using the update method?



      Thanks!



      # -*- coding: utf-8 -*-

      import sys
      import numpy as np

      from PyQt5 import QtCore, QtWidgets, uic

      import matplotlib
      matplotlib.use('QT5Agg')

      import matplotlib.pylab as plt

      from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
      from matplotlib.backends.backend_qt5agg import FigureCanvas, NavigationToolbar2QT as NavigationToolbar
      from matplotlib.figure import Figure

      class MyWindow(QMainWindow):

      def __init__(self):

      super(MyWindow, self).__init__()
      uic.loadUi('test.ui', self)

      # test data
      data = np.array([0.7,0.7,0.7,0.8,0.9,0.9,1.5,1.5,1.5,1.5])
      fig, ax1 = plt.subplots()
      bins = np.arange(0.6, 1.62, 0.02)
      n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)

      # plot
      self.plotWidget = FigureCanvas(fig)
      self.lay = QtWidgets.QVBoxLayout(self.content_plot)
      self.lay.setContentsMargins(0, 0, 0, 0)
      self.lay.addWidget(self.plotWidget)

      # add toolbar
      self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(self.plotWidget, self))

      # button event
      self.pushButton.clicked.connect(self.update)

      # show window
      self.show()

      #########################################

      def update(self):

      data = np.array([0.1,0.1,0.1,0.1,0.3,0.3,1.7,1.7,1.7,1.7])
      fig, ax1 = plt.subplots()
      bins = np.arange(0.6, 1.62, 0.02)
      n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)

      # show plot in canvas
      self.plotWidget = FigureCanvas(fig)
      self.toolbarWidget = NavigationToolbar(self.plotWidget, self)


      if __name__ == '__main__':

      app = QtWidgets.QApplication(sys.argv)
      window = MyWindow()
      sys.exit(app.exec_())






      python matplotlib pyqt5






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 12 '18 at 8:17









      schlenzmeisterschlenzmeister

      348




      348






















          1 Answer
          1






          active

          oldest

          votes


















          1














          You should not create a new figure, instead, reuse the axes that you already have. That means that you have to keep a reference to that object first.



          I cannot test the code right now, but you should do something like



          def __init__(self):
          (...)
          self.fig, self.ax = plt.subplots()
          (...)

          def update(self):
          data = (...)
          self.ax.cla() # clear the axes content
          self.ax.hist(...)
          self.fig.canvas.draw_idle() # actually draw the new content





          share|improve this answer























          • Thanks! That is easy... :)

            – schlenzmeister
            Nov 12 '18 at 14:44










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53258160%2fupdate-an-embedded-matplotlib-plot-in-a-pyqt5-gui-with-toolbar%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You should not create a new figure, instead, reuse the axes that you already have. That means that you have to keep a reference to that object first.



          I cannot test the code right now, but you should do something like



          def __init__(self):
          (...)
          self.fig, self.ax = plt.subplots()
          (...)

          def update(self):
          data = (...)
          self.ax.cla() # clear the axes content
          self.ax.hist(...)
          self.fig.canvas.draw_idle() # actually draw the new content





          share|improve this answer























          • Thanks! That is easy... :)

            – schlenzmeister
            Nov 12 '18 at 14:44















          1














          You should not create a new figure, instead, reuse the axes that you already have. That means that you have to keep a reference to that object first.



          I cannot test the code right now, but you should do something like



          def __init__(self):
          (...)
          self.fig, self.ax = plt.subplots()
          (...)

          def update(self):
          data = (...)
          self.ax.cla() # clear the axes content
          self.ax.hist(...)
          self.fig.canvas.draw_idle() # actually draw the new content





          share|improve this answer























          • Thanks! That is easy... :)

            – schlenzmeister
            Nov 12 '18 at 14:44













          1












          1








          1







          You should not create a new figure, instead, reuse the axes that you already have. That means that you have to keep a reference to that object first.



          I cannot test the code right now, but you should do something like



          def __init__(self):
          (...)
          self.fig, self.ax = plt.subplots()
          (...)

          def update(self):
          data = (...)
          self.ax.cla() # clear the axes content
          self.ax.hist(...)
          self.fig.canvas.draw_idle() # actually draw the new content





          share|improve this answer













          You should not create a new figure, instead, reuse the axes that you already have. That means that you have to keep a reference to that object first.



          I cannot test the code right now, but you should do something like



          def __init__(self):
          (...)
          self.fig, self.ax = plt.subplots()
          (...)

          def update(self):
          data = (...)
          self.ax.cla() # clear the axes content
          self.ax.hist(...)
          self.fig.canvas.draw_idle() # actually draw the new content






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 12 '18 at 12:10









          Diziet AsahiDiziet Asahi

          8,70831729




          8,70831729












          • Thanks! That is easy... :)

            – schlenzmeister
            Nov 12 '18 at 14:44

















          • Thanks! That is easy... :)

            – schlenzmeister
            Nov 12 '18 at 14:44
















          Thanks! That is easy... :)

          – schlenzmeister
          Nov 12 '18 at 14:44





          Thanks! That is easy... :)

          – schlenzmeister
          Nov 12 '18 at 14:44



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53258160%2fupdate-an-embedded-matplotlib-plot-in-a-pyqt5-gui-with-toolbar%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

          Edmonton

          Crossroads (UK TV series)