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()
Related
My code is as below.
....(omission)...
sympy.plot(func, (x,-2,20))
Then the plot window successfully pops up but it doesn't close(doesn't terminate).
Is there a function similar to plt.close() in sympy plot methods?
Thank you.
Sadly, it's not fully implemented. Assuming that you are running your code from a Python or IPython console, to achieve your objective we need to modify a few methods.
from sympy import *
var("x")
from sympy.plotting.plot import Plot, MatplotlibBackend
def show(self):
self.process_series()
self.fig.tight_layout()
self.plt.show(block=False)
MatplotlibBackend.show = show
def close(self):
self._backend.close()
Plot.close = close
p = plot(sin(x))
# at this point the matplotlib window is "detached" from the console.
# you can execute other commands. Finally, when you are ready to close
# the figure, run this:
p.close()
Disclaimer: I am new to Python and I have the latest Anaconda-Python (3.8.3) installed in my computer. My code is
if __name__ == '__main__':
import imageio
import matplotlib.pyplot as plt
plt.clf()
pic = imageio.imread('Photo_Vikash_pandey.jpg')
plt.figure(figsize = (15,15))
plt.imshow(pic)
Every time I run the code I see images piled up in the adjoining window of Spyder IDE. I want that every time I run the code, it has no history of its previous execution. I do not wish to see image display from previous runs of the code.
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.
Is there a way to close a pyplot figure in OS X using the keyboard (as far as I can see you can only close it by clicking the window close button)?
I tried many key combinations like command-Q, command-W, and similar, but none of them appear to work on my system.
I also tried this code posted here:
#!/usr/bin/env python
import matplotlib.pyplot as plt
plt.plot(range(10))
def quit_figure(event):
if event.key == 'q':
plt.close(event.canvas.figure)
cid = plt.gcf().canvas.mpl_connect('key_press_event', quit_figure)
plt.show()
However, the above doesn't work on OS X either. I tried adding print statements to quit_figure, but it seems like it's never called.
I'm trying this on the latest public OS X, matplotlib version 1.1.1, and the standard Python that comes with OS X (2.7.3). Any ideas on how to fix this? It's very annoying to have to reach for the mouse every time.
This is definitely a bug in the default OS X backend used by pyplot. Adding the following two lines at the top of the file switches to a different backend that works for me, if this helps anyone else.
import matplotlib
matplotlib.use('TKAgg')
I got around this by replacing
plt.show()
with
plt.show(block=False)
input("Hit Enter To Close")
plt.close()
A hack at its best, but I hope that helps someone
use interactive mode:
import matplotlib.pyplot as plt
# Enable interactive mode:
plt.ion()
# Make your plot: No need to call plt.show() in interactive mode
plt.plot(range(10))
# Close the active plot:
plt.close()
# Plots can also be closed via plt.close('all') to close all open plots or
# plt.close(figure_name) for named figures.
Checkout the "What is interactive mode?" section in this documentation
Interactive mode can be turned off at any point with plt.ioff()
When you have focus in the matplotlib window, the official keyboard shortcut is ctrl-W by this:
http://matplotlib.org/1.2.1/users/navigation_toolbar.html
As this is a very un-Mac way to do things, it is actually cmd-W. Not so easy to guess, is it?
If you are using an interactive shell, you can also close the window programmatically. See:
When to use cla(), clf() or close() for clearing a plot in matplotlib?
So, if you use pylab or equivalent (everything in the same namespace), it is just close(fig). If you are loading the libraries manually, you need to take close from the right namespace, for example:
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([0,1,2],[0,1,0],'r')
fig.show()
plt.close(fig)
The only catch here is that there is no such thing as fig.close even though one would expect. On the other hand, you can use plt.close('all') to regain your desktop.
This question already has answers here:
Interactive(?) plotting in Spyder with matplotlib
(2 answers)
Closed 3 months ago.
I need to use interactive mode when plotting with matplotlib (it should be a script, not python or ipython console). But setting plt.ion() causes a strange bug (?). When I try to plot my figure (I don't think it really matters, what I do exactly, because in non-interactive mode it works perfectly fine) I don't see it - I get a blank grey window for split-second, which momentarily disappears and the programme exits.
If I explicitly add plt.draw() (and plt.pause(1) to see the result), I see that the figure appears as expected. If I do the same after modifications I want to do to the figure when it is visible, the figure changes. But the window still disappears after the pause is over.
I run it in Spyder with Qt4Agg as a backend under Ubuntu. Tried running the script from terminal as python my_script.py, the result is identical.
What could be the problem? How do I stop the figure from disappearing when in interactive mode?
UPDATE
Working example:
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
x = np.linspace(1, 10)
y = np.sin(x)
plt.plot(x, y)
plt.draw()
plt.pause(1)
If I run this code I see the sine plot for 1 second, then the window disappears.
UPDATE 2
I found a solution here: https://stackoverflow.com/a/10724654/1304161
If I set the run options in Spyder correctly, it works perfectly fine. Although running it in gnome-terminal doesn't work, I don't really need it. Hopefully, there won't be a problem with this when it becomes a part of a GUI app...
I found a solution here: https://stackoverflow.com/a/10724654/1304161
If I set the run options in Spyder correctly, it works perfectly fine. Although running it in gnome-terminal doesn't work, I don't really need it. Hopefully, there won't be a problem with this when it becomes a part of a GUI app. I will be back, if it will be a problem then :)
You can make it work by adding these two lines at the end:
plt.ioff()
plt.show()
So this program works fine:
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
x = np.linspace(1, 10)
y = np.sin(x)
plt.plot(x, y)
plt.draw()
plt.ioff()
plt.show()
To display multiple figures at different times, you can use code.interact(local=locals()), after plt.show() to pause the Python interpreter until a Ctrl-Z is pressed in the Python Shell:
import code
import matplotlib.pyplot as plt
import numpy as np
# Start pyplot's "interactive mode" which lets you run plt.show multiple times
plt.ion()
x = np.linspace(1, 10)
y = np.sin(x)
# PLOT #1 - displayed
plt.plot(x, y)
plt.draw()
plt.show()
# Wait for figure to be closed AND Ctrl-Z pressed in Python Shell
code.interact(local=locals())
print("Some more code can go here...")
# PLOT #2 - displayed
plt.plot(x, y)
plt.show()
# Wait for figure to be closed AND Ctrl-Z pressed in Python Shell
code.interact(local=locals())