matplotlib: no interactive window shown - python

>>> from pylab import *
>>> plot(1)
[<matplotlib.lines.Line2D object at 0x2a9f9ce550>]
>>> show()
Nothing happens. No error message. No interactive window.
Someone know what's the problem could be?
The OS is RH4 and DISPLAY is set properly. Other GUI application can work fine.

Oz123 is right, this can be caused by the wrong backend being set "svg","ps", and "cairo", for example, don't seem to support show() see this post for examples of how to change it, get "GTKcairo" working if it's not, or change the default

Related

Python Matplotlib: Clear figure when figure window is not open

I'm working with matplotlib plotting and use ioff() to switch interactive mode off to suppress the automatic opening of the plotting window on figrue creation. I want to have full control over the figure and only see it when explicitely using the show() command.
Now apparently the built-in commands to clear figures and axes do not work properly anymore.
Example:
import numpy as np
import matplotlib.pyplot as mpp
class PlotTest:
def __init__(self,nx=1,ny=1):
# Switch off interactive mode:
mpp.ioff()
# Create Figure and Axes:
self.createFigure(nx, ny)
def createFigure(self,nx=1,ny=1):
self.fig, self.axes = mpp.subplots(nx,ny)
if nx*ny == 1:
self.axes = np.array([self.axes])
def linePlot(self):
X = np.linspace(0,20,21)
Y = np.random.rand(21)
self.axes[0].plot(X,Y)
P = PlotTest()
P.linePlot()
P.fig.show()
Now I was thinking I could use P.fig.clear() any time to simply clear P.fig, but apparently that's not the case.
Writing P.fig.clear() directly into the script and execute it together it works and all I see is an empty figure. However that's rather pointless as I never get to see the actual plot like that.
Doing P.fig.clear() manually in the console does not do anything, regardless if the plot window is open or not, all other possible commands fail as well:
P.fig.clf()
P.axes[0].clear()
P.axes[0].cla()
mpp.clf()
mpp.cla()
mpp.close(P.fig)
Wrapping the command into a class method doesn't work either:
def clearFig(self):
self.fig.clear()
EDIT ================
After a clear() fig.axes is empty, yet show() still shows the old plot with the axes still being plotted.
/EDIT ================
Is it because I switched off interactive mode?
If you add a call to plt.draw() after P.fig.clear() it clears the figure. From the docs,
This is used in interactive mode to update a figure that has been altered, but not automatically re-drawn. This should be only rarely needed, but there may be ways to modify the state of a figure with out marking it as stale. Please report these cases as bugs.
I guess this is not a bug as you have switched off interactive mode so it is now your responsibility to explicitly redraw when you want to.
You can also use P.fig.canvas.draw_idle() which could be wrapper in the class as clearFigure method.

Matplotlib "pick_event" not working in embedded graph with FigureCanvasTkAgg

I'm trying to handle some events to perform user interactions with embedded subplots into a Tkinter frame. Like in this example
Works fine with "key_press_event" and "button_press_event", but does not work with "pick_event".
I modified that example from the link, just adding the following piece of code after the mpl_connect calling:
def on_button_press(event):
print('you pressed mouse button')
canvas.mpl_connect('button_press_event', on_button_press)
def on_pick(event):
print('you picked:',event.artist)
canvas.mpl_connect('pick_event', on_pick)
Why "pick_event" doesn't work into embedded graphs? And how do get it to work?
My configurations detailed:
Windows 10
Python 3.5 (conda version)
Matplotlib 1.5.3 installed via pip
Thanks in advance!
Well, I solved it...
Most events we just need to use mpl_connect method to the magic happen. My mistake is that I didn't notice that we need to say explictly that our plot is "pickable" putting a argument picker=True to only triggers the event if clicked exacly into the artist, and picker=x where x is an integer that is the pixel tolerance for the trigger. So beyond the changes I inserted for pick in the question, we should replace
a.plot(t, s) for a.plot(t, s,picker=True) or a.plot(t, s,picker=10), e.g.

Why can't I change the icon on a tkMessagebox.askyesno() on OS X?

tkMessageBox.askyesno('Title', 'Message', icon=tkMessageBox.WARNING) on OS X just gives me the rocket icon.
I know there is some weirdness with OS X and tkMessageBox icons because tkMessageBox.showerror() just shows the rocket icon, but tkMessageBox.showwarning shows a yellow triangle (with a small rocket in the corner)
Is this is a bug?
Is there some workaround to get a warning triangle and Yes/No buttons without having to resort to making my own message box window from scratch?
I found a solution:
tkMessageBox.askretrycancel(title, message, type=tkMessageBox.YESNO)
seems to work, but both buttons presses return False, so it's not of any use.
tkMessageBox.showwarning(title, message, type=tkMessageBox.YESNO)
does also work work, but be aware that it returns 'yes' or 'no', not True or False. It's the only real option though.
I would still be interested if anyone can tell me whether it is a bug.
You can use icon='warning' instead of icon=tkMessageBox.WARNING
I just tried that on Windows. Sorry I don't have OSX to test

Close pyplot figure using the keyboard on Mac OS X

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.

OSX How to bring Matplotlib window to the front?

I'm trying to use matplotlib for chart visualizations, but it is very annoying to look for a window each time I run the project. Is there any way to force it to be on top of other windows? I use OSX 10.8 and PyCharm IDE and already tried
from pylab import get_current_fig_manager()
get_current_fig_manager().window.raise_()
Which fails with
AttributeError: 'FigureManagerMac' object has no attribute 'window'
I'd appreciate any other ideas.
you're call to window.raise_() is from PyQT.
Indeed, you can raise the window in this way but you need to:
set PyQT4 as your backend before you do any other business with matplotlib
And
import matplotlib
matplotlib.use('Qt4Agg')
Either you fix you import statement (remove the brackets) or save yourself the import and access the window through the figure
with
window = fig.canvas.manager.window
Only then you can call window.raise_() and the window will be in front of pycharm.
This works for me from IPython:
from pylab import get_current_fig_manager
fm = get_current_fig_manager()
fm.show()
I haven't found a case in which show() doesn't work by itself, though.
[cphlewis] had a great answer. I found myself doing this so often that I def a little function to pop all my windows up to the surface:
def pop_all():
#bring all the figures hiding in the background to the foreground
all_figures=[manager.canvas.figure for manager in matplotlib.\
_pylab_helpers.Gcf.get_all_fig_managers()]
[fig.canvas.manager.show() for fig in all_figures]
return len(all_figures)

Categories