1

I wrote a program in Python 3.5, PyQt5 and Matplotlib 1.5.3, where I used the pyplot interactive mode. Here a minimal example:

import numpy as np
import matplotlib.pyplot as plt

plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid(True)

for i in range (0, 10):
    plt.scatter(i, np.sin(i))
    fig.canvas.draw()

plt.ioff()
plt.show()

Because now I am writing the GUI and I can't use pyplot, because its own eventloop interferes with the Qt one, I was re-writing that part of the code, but I didn't find the equivalent of interactive mode into the Matplotlib widget with PyQt5. This is the basic example:

import sys
import time

from matplotlib.figure import Figure

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

import numpy as np
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget

if __name__ == '__main__':

    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.grid(True)

    for i in range (0, 10):
        ax.scatter(i, np.sin(i))
        fig.canvas.draw()

    ui = QWidget()

    toolbar = NavigationToolbar(canvas, ui, coordinates=True)

    vbox = QVBoxLayout()
    vbox.addWidget(canvas)
    vbox.addWidget(toolbar)
    ui.setLayout(vbox)
    ui.show()

    app = QApplication(sys.argv)
    sys.exit(app.exec_())

I would like, as the first example, the plot is updated at each iteration. How can I modify the code?

Thanks! Ciccio

cicciodevoto
  • 305
  • 4
  • 19
  • The question "duplicated" and its answer show how to use *animations* but not the other features of interactive mode (such as zooming and panning) that you would get with a non-embedded matplotlib graph. For those interested, [this](https://stackoverflow.com/questions/50499120/matplotlib-navigationtoolbar-embedded-in-pyqt5?rq=1) might help. – Guimoute Mar 14 '19 at 14:46

1 Answers1

0

This question is showing how to do interactive animations in matplotlib and PyQt. So in order to see how it's done simply refer to this or any other related questions.

The first problem of your code is that it it's performing the plot loop before the window is even shown on the screen. Very generally in GUIs, it's always preferable to first initialize the window, then start whatever should happen inside.

The second problem, which is at the moment hidden behind the first, would be that you perform your plotting loop inside the GUIs main loop such that for longer looping times, the GUI would freeze.

Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Hi, thanks for the answer and the clarifications, I will study the animation class and I will try, I think it can solve my problem. – cicciodevoto Dec 05 '16 at 12:38