pyqtgraph plot does not show up when program executed - python

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.

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_()
Note: do not use any IDE since many can not handle the event loop correctly, execute it from the terminal.

Related

Matplotlib not showing plot when program is executed in the VS Code terminal

I have this simple program here
import numpy as np
import matplotlib.pyplot as plt
num_of_intervals = 2000
x = np.linspace(-10,10,num=num_of_intervals)
y_inputs = 1/(1+np.exp(-x)) # SIGMOID FUNCTION
plt.figure(figsize = (15,9))
plt.plot(x,y_inputs,label = 'Sigmoid Function')
plt.vlines(x=0, ymin = min(y_inputs), ymax=max(y_inputs), linestyles='dashed')
plt.title('Sigmoid Function')
plt.show()
When the above program is ran in the vscode terminal. The plot cannot be seen (usually a pop-up window appears showing the plot).
But when the program is ran in the Ubuntu terminal, the plot can be seen as a pop-up window.
Any idea how I can solve this issue with vscode.
OS : Ubuntu 20.04
Visual Studio Code 1.54.3
Python : 3.8.5
Double check that this option is turned on in Settings: terminal.integrated.inheritEnv

python Ginput working in spyder but not working from terminal or command window

I have a program to scatter plot eigenvalues and from the user click to retrieve the selected number/coordinate and use that input for further analysis. The program is working fine in Spyder console ( I am using python 2.7.16 and matplotlib 2.2.3). But when I execute the same code from the mac terminal, it is showing the plot but not recognizing the user click. (I have checked the same code from windows command terminal and it is also not working there even though it is working in spyder installed in my windows system). The program is also not showing any error. A sample program is provided here for reference.
import matplotlib.pyplot as plt
import numpy as np
n = 10
real_part = np.random.normal(size=n)
imag_part = np.random.normal(size=n)
z = np.array(real_part, dtype=complex)
z.imag = imag_part
fig,ax = plt.subplots(figsize=(8,5))
ax.scatter(z.real,z.imag,marker='x',color='r')
plt.grid(which='both',axis='both')
plt.title('Complex plot')
plt.show()
userInput=plt.ginput(n=1, timeout=30, show_clicks=True)
print("User Input is %s"%userInput)
Any help on this would be highly appreciated.
Thanks in advance.

Python - How do I get my GUI to display in Spyder

I'm new to creating GUI's in Python and can't seem to get over the first hurdle.
I'm using Anaconda - Spyder and I normally run all (mainly mathematical) code through this (and the IPython console?).
My issue is that when I run the code below I'm expecting it to display a simple blank window but nothing happens.
Is Spyder/IPython not the best way to do this or is there an issue with my code?
I've tried using the command prompt by typing "python TestScript.py" whilst in the correct directory but I get an error saying 'Python is not recognised as a internal or external command'. Do I need to set up cmd to use Anaconda?
import sys
from PyQt5.QtWidgets import QApplication, QWidget
if __name__ == '__main__':
app = QApplication(sys.argv)
w = QWidget()
w.resize(250,150)
w.move(30,30)
w.setWindowTitle('Simple Window')
w.show
sys.exit(app.exec_())
Clearing this one up, as the answer was posted in the comments by Patrick Artner.
Simply adding () after w.show solved the problem.

Pyside UI pops up and then disappears when run from cmd before it can be used?

I am fairly new to python and have made a simple UI using pyside. When run from inside the anaconda IDE the UI works fine, but when I run it using anaconda from the command line \python.exe 'runquacker.py' the UI flashes up and disappears immediately.
The initial script is:
from PySide.QtCore import *
from PySide.QtGui import *
import sys
import quacker
class MainDialog(QDialog, quacker.Ui_Dialog):
def __init__(self, parent=None):
super(MainDialog, self).__init__(parent)
self.setupUi(self)
app = QApplication(sys.argv)
form = MainDialog()
form.show()
The rest of the UI is in quacker.py which collects a bunch of variables from the user, before executing a further analysis.py program using a subprocesscall. The variables are all passed in this way because thats the only way I could get pyside to work with my script!
e.g. For two variables 'plots' and 'block':
subprocess.call([sys.executable, 'd:\\py\\anaconda\\analysis.py', str(plots), str(block)], shell=True)
Ive tried putting a raw_input('Blah..') in a few places but it just causes the program to hang or nothing at all.
Using \python.exe -i runquacker.py also causes the program to hang.
Thanks
You need to add this line at the end of your script: app.exec_()
That's because you need to actually execute your Qt application if you whant to see something.
I'm not pretty sure why it works in Anaconda but if you are using some IDE like Spyder I think it works because Spyder is already running in Qt (so it called QApplication.exec_ before).

Stop python GUI program from exiting when run from CLI

How can easily I make a blocking GUI app on OS X?
I have a simple python plotting program. When I run it from inside an existing python interactive session, or from within iPython, the GUI window is displayed, and I can see it and interact with it. When I run the .py file from the CLI, the GUI flashes and closes immediately.
I would like to run this from the command line and have the GUI remain.
if __name__ == "__main__":
import matplotlib
from matplotlib import pyplot
data = range(1,10)
fig = pyplot.plot(data)
pyplot.show()
It sounds as though interactive mode has been enabled somehow, although I'm not sure where. Try it like this:
def main():
import matplotlib.pyplot as plt
data = range(1,10)
fig = plt.plot(data)
plt.ioff() # turns interactive mode OFF, should make show() blocking
plt.show()
if __name__ == "__main__":
main()

Categories