pyqtgraph plot does not show up when program executed

Viewed 2329

I am trying to learn how to use pyqtgraph and tried to run the following first simple example given in the above document:

#!/usr/bin/env python3

import pyqtgraph as pg

import numpy as np

x = np.random.normal(size=1000)

y = np.random.normal(size=1000)

pg.plot(x,y,pen=None,symbol='o',title='first graph')

I am using python 3.5.3 on a Raspberry Pi 3 with Raspbian Stretch.

If I run the above program in Thonny or IDLE, the program runs without any error but does not display any output.

Similarly, if I run the program at the Linux command prompt by simply calling the program name (I have made it executable using chmod +x) or by typing python3 followed by the program name, still it does not show anything.

However, if I type python3 at the Linux prompt and get a python prompt and then run each of the lines in the program one by one, then it displays a scatter plot in a window titled "first graph" as expected.

Can someone please let me know what I need to do to get the code to display the graph when run through the Thonny or IDLE or by calling it as a program?

Thank you.

1 Answers

Every GUI needs an event loop, and in your case you are not creating it, in the following code I show how to do it:

#!/usr/bin/env python3

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np


x = np.random.normal(size=1000)
y = np.random.normal(size=1000)
pg.plot(x,y,pen=None,symbol='o',title='first graph')


if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

enter image description here

Note: do not use any IDE since many can not handle the event loop correctly, execute it from the terminal.

Related