wxPython Matplotlib.pyplot Conflict? - python

I have met this pretty weird bug when using wxPython today. This simple code works fine:
import wx
app = wx.App()
frame = wx.Frame(None, -1, 'simple.py')
frame.Show()
app.MainLoop()
However, once I add an import statement for matplotlib.pyplot at top:
import matplotlib.pyplot as plt
# then same code as above...
the simple window does not show up anymore (without errors, program halts). Anyone know what the problem is?
Env: macOS High Sierra, Python 3.6.3, wxPython 4.0.0b2, matplotlib 2.1.0
Thanks!

I suspect that it is crashing because you don't have a specific library available for the backend, probably python3-tk
Try:
from matplotlib import use
use('WXAgg')
from matplotlib import pyplot as plt
import wx
app = wx.App()
frame = wx.Frame(None, -1, 'simple.py')
frame.Show()
app.MainLoop()

I had this exact same problem. It only happens on macOS for me. I can run the program fine in Windows, but not Mac. I tested different versions of matplotlib to no avail. I wanted to test against the "classic" version of wxpython but I couldn't get it to download correctly from SourceForge.
I got around it by importing matplotlib inside of my function that did the plotting. This ran without errors but also produced some informative warnings:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/cbook/deprecation.py:107: MatplotlibDeprecationWarning: The WX backend is deprecated. It's untested and will be removed in Matplotlib 3.0. Use the WXAgg backend instead. See Matplotlib usage FAQ for more info on backends. Use WXAgg instead.
warnings.warn(message, mplDeprecation, stacklevel=1)
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_wx.py:319: wxPyDeprecationWarning: Call to deprecated item. Use DrawText instead.
gfx_ctx.DrawRotatedText(s, x - xo, y - yo, rads)
So it looks like the problem is due to some wx deprecation inside of matplotlib.
Rolf of Saxony's answer also worked for me and did not produce the warnings.

Related

How can I display an image on VS Code and PyCharm?

I want to choose the best IDE for Python programming so I'm testing different softwares but I have problem.
When I try this code blocks on VS Code I don't see any error but the image is not showing
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread('exit-ramp.jpg')
plt.imshow(image)
VS Code
When I try run the same code on PyCharm I see some errors
PyCharm
But when I run the same code on Jupyter Notebook it works. What can I do?
Bro, try that:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread('exit-ramp.jpg')
plt.imshow(image)
plt.show()
i've made a test in my vscode.
Few weeks ago i used a lot pycharm... but i get some library errors with pandas and pycharm its a little bit heavy.
VSCODE its light and i didnt get any library error that i had with pycharm.
I believe this is a backend problem to be changed in matplotlib. If you start your Python shell whether you are in a bash shell or in vscode, you should use a backend that will show the plot. Otherwise the plt.show() call is required.
So, one solution is to change the backend either manually in you Python shell or when starting the Python shell as explained here below.
Note, however, that I always use the qt5 backend but got the same issue as yours: no plot appears. I changed to the Qt5Agg backend and it worked for me (providing PyQt5 is installed).
So, first solution, you can try to set the backend when starting the Python shell:
ipython --pylab Qt5Agg
You should use a GUI backend amongst the possible backend. If you do not known, try to replace Qt5Agg by auto
The second solution consists in changing the backend manually once in the Python shell:
import matplotlib as plt
plt.use('Qt5Agg')
Right click on your code -> Run current file in interactive window.

%matplotlib inline doesn't work on iPython and Jupyter console

I'm trying out Jupyter console for the first time, but can't get the %matplotlib inline magic to work. Below is a screenshot of an example session:
The plot shows in a separate window after I run Line 6, and Line 7 doesn't do anything.
When I run %matplotlib --list, inline is given as one of the options:
Available matplotlib backends: ['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt',
'nbagg', 'agg', 'gtk', 'tk', 'ipympl', 'inline']
When I try to use another backend, say qt5, it gives an error message because I don't have any Qt installed.
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5, or PySide
package to be installed, but it was not found.
Running %matplotlib?? reads:
If you are using the inline matplotlib backend in the IPython Notebook
you can set which figure formats are enabled using the following::
In [1]: from IPython.display import set_matplotlib_formats
In [2]: set_matplotlib_formats('pdf', 'svg')
The default for inline figures sets `bbox_inches` to 'tight'. This can
cause discrepancies between the displayed image and the identical
image created using `savefig`. This behavior can be disabled using the
`%config` magic::
In [3]: %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
But I don't know if it's something I can tweak around to solve my issue.
When I try it the magic IPython console, it says inline is an Unknown Backend.
UnknownBackend: No event loop integration for u'inline'. Supported event loops are: qt,
qt4, qt5, gtk, gtk2, gtk3, tk, wx, pyglet, glut, osx
I've also found this issue on github after some googling but I don't even know if it's relevant to my situation (most of their conversation didn't make sense to me lol).
Lastly, I'm not sure if this issue is related at all, but here it is, just in case: when I try to open Vim in Jupyter via the !vim command, it glitches pretty badly, preventing me from even exiting out of Jupyter itself without closing the terminal altogther. Vim works perfectly fine when called inside IPython console, however.
I'm using matplotlib 2.0.0.
If anyone could help me figure this out, that'd be great! Thank you!
You’re running a console which is completely text based and incapable of showing images. Therefore, although inline is available, it's not producing inline output.
I'm not sure why it doesn't throw an error, though, which it does in my case:
You can use %matplotlib inline in a GUI console, like Jupyter QTConsole
or in a jupyter notebook in the browser
%matplotlib without the inline works for me (I'm using osx and IPython 7.0.1)
If you're running an old version of ipython try %pylab inline instead. See notes in this tutorial

Making Matplotlib and GTK3 work on python3 windows

I'm trying to make GTK3 and Python3 work under windows to my project.
I have an continuum anaconda setup with a 32-bit python 3.4 and Matplotib via
conda install matplotlib.
I've installed PyGobject(https://sourceforge.net/projects/pygobjectwin32/) and installed GTK+ / Glade via the installer.
The basic exemple from the GTK3 tutorial works well (empty screen)
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
I want now to embed matplotlib in gtk, I got the example from matplotlib (http://matplotlib.org/examples/user_interfaces/embedding_in_gtk3.html)
I saw then that I needed cairocffi because some incompabilities. (PyCairo has no support for a matplotlib function)
I got the windows binaries for cffi from Gohlke
And finnaly did a
pip install cairocffi
And now I just get a python.exe stopped working.
Tried with GTK3agg and GTK3Cairo backends and I have the same result
Looking around I found that maybe the cairo version is outdated for the functions used by matplotlib, but I dont know how to proceed.
Cairocffi works if I try running something else.
More information (from the comment below):
I still got an unhandled win32 error. I managed to open the error and it says:
Unhandled exception at 0x08CF6D58 (libcairo-2.dll) in python.exe:
0xC0000005: Access violation reading location 0x000000A8.
If there is a handler for this exception, the program may be safely continued.
It just crashes...
I've had my share of problems using matplotlib in Python3 + Gtk3. I found this cookbook page with working examples. Try to run the examples in the cookbook - particularly the simplest one:
#!/usr/bin/python3
from gi.repository import Gtk
from matplotlib.figure import Figure
from numpy import arange, pi, random, linspace
import matplotlib.cm as cm
#Possibly this rendering backend is broken currently
#from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo as FigureCanvas
myfirstwindow = Gtk.Window()
myfirstwindow.connect("delete-event", Gtk.main_quit)
myfirstwindow.set_default_size(400, 400)
fig = Figure(figsize=(5,5), dpi=100)
ax = fig.add_subplot(111, projection='polar')
N = 20
theta = linspace(0.0, 2 * pi, N, endpoint=False)
radii = 10 * random.rand(N)
width = pi / 4 * random.rand(N)
bars = ax.bar(theta, radii, width=width, bottom=0.0)
for r, bar in zip(radii, bars):
bar.set_facecolor(cm.jet(r / 10.))
bar.set_alpha(0.5)
ax.plot()
sw = Gtk.ScrolledWindow()
myfirstwindow.add(sw)
canvas = FigureCanvas(fig)
canvas.set_size_request(400,400)
sw.add_with_viewport(canvas)
myfirstwindow.show_all()
Gtk.main()
Also, not that you need a fairly recent version of matplotlib to make things work on Python3.
If you still have problems, please show us the complete error message.
Note: I tested this on Linux (don't have Windows), but, from you description of problems, the issue is (was) a common one.
I have the same issue on Windows since years. The documentation of matplotlib 2.0.0 realease states that Gtk3 backend is not supported on Windows. Recently, I had an issue running the Gtk3Agg backend under Linux (Ubuntu). In both cases, it is always related to Cairo.
Thus, I wrote my own implementation of this backend, you can find it here. import the FigureCanvasGtk3Agg from my module and use it the same way as the official one. It lacks some features, but, if you just want to display a plot, it'll do the job.
You can try the module by running it, it should display a simple colorful graph in a window. I tried it under both Linux and Windows and had no issue.
How does it works:
The trick is to avoid importing Cairo in Python3 as it usually doesn't work (to my experience). It is done by using a GdkPixbuf.
Then Gdk.cairo_set_source_pixbuf does the rest of the job along with calling two methods of the cairo context provided by Gtk in the 'draw-event' callback. Cairo is never imported in the module.

Jupyter Notebook ImportError, %matplotlib qt

I am using
%matplotlib inline
to display plots inside the notebook. I would like to disable this for several cells. So, I try
%matplotlib qt
This outputs the following error:
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5,
or PySide package to be installed, but it was not found.
I am not sure how to solve this, as everything is up to date.
How can I solve the above?
Is there another way to disable %matplotlib inline in a certain cell without restarting the entire kernel?
You might be able to use plt.switch_backend, although as the documentation states, this is an experimental feature. The following works for me, using matplotlib 1.5 and an IPython 4.0.1:
In [1]: from matplotlib import pyplot as plt
In [2]: import numpy as np
# plot appears inline (default)
In [3]:plt.plot(np.random.randn(10))
Out[3]:[<matplotlib.lines.Line2D at 0x7fac4408e390>]
In [4]: plt.switch_backend('QtAgg4')
# plot appears inside a separate Qt4 window
In [5]:plt.plot(np.random.randn(10))
Out[5]:[<matplotlib.lines.Line2D at 0x7fac3b408a90>]
You might need to change 'QtAgg4' according to whichever version of PyQt you have installed - this could be the cause of the error you mentioned in the question. Another interactive backend that should work on Mac would be 'CocoaAgg'. If the images are very large you could also use the 'Agg' backend to suppress plotting altogether, and instead save the resulting figure(s) straight to disk.
If you don't have a specific backend installed use "agg":
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
Reference: https://github.com/matplotlib/matplotlib/issues/9017

Plotting window doesn't show up with pylab [duplicate]

I just installed matplotlib in Ubuntu 9.10 using the synaptic package system.
However, when I try the following simple example
>>> from pylab import plot;
>>> plot([1,2,3],[1,2,3])
[<matplotlib.lines.Line2D object at 0x9aa78ec>]
I get no plot window. Any ideas on how to get the plot window to show?
You can type
import pylab
pylab.show()
or better, use ipython -pylab.
Since the use of pylab is not recommended anymore, the solution would nowadays be
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.show()
pylab.show() works but blocks (you need to close the window).
A much more convenient solution is to do pylab.ion() (interactive mode on) when you start: all (the pylab equivalents of) pyplot.* commands display their plot immediately. More information on the interactive mode can be found on the official web site.
I also second using the even more convenient ipython -pylab (--pylab, in newer versions), which allows you to skip the from … import … part (%pylab works, too, in newer IPython versions).
Try this:
import matplotlib
matplotlib.use('TkAgg')
BEFORE import pylab
The code snippet below works on both Eclipse and the Python shell:
import numpy as np
import matplotlib.pyplot as plt
# Come up with x and y
x = np.arange(0, 5, 0.1)
y = np.sin(x)
# Just print x and y for fun
print x
print y
# Plot the x and y and you are supposed to see a sine curve
plt.plot(x, y)
# Without the line below, the figure won't show
plt.show()
Any errors show up? This might an issue of not having set the backend. You can set it from the Python interpreter or from a config file (.matplotlib/matplotlibrc) in you home directory.
To set the backend in code you can do
import matplotlib
matplotlib.use('Agg')
where 'Agg' is the name of the backend. Which backends are present depend on your installation and OS.
http://matplotlib.sourceforge.net/faq/installing_faq.html#backends
http://matplotlib.org/users/customizing.html
Modern IPython uses the "--matplotlib" argument with an optional backend parameter. It defaults to "auto", which is usually good enough on Mac and Windows. I haven't tested it on Ubuntu or any other Linux distribution, but I would expect it to work.
ipython --matplotlib
If you encounter an issue in which pylab.show() freezes the IPython window (this may be Mac OS X specific; not sure), you can cmd-c in the IPython window, switch to the plot window, and it will break out.
Apparently, future calls to pylab.show() will not freeze the IPython window, only the first call. Unfortunately, I've found that the behavior of the plot window / interactions with show() changes every time I reinstall matplotlib, so this solution may not always hold.
If you are starting IPython with the --pylab option, you shouldn't need to call show() or draw(). Try this:
ipython --pylab=inline
--pylab no longer works for Jupyter, but fortunately we can add a tweak in the ipython_config.py file to get both pylab as well as autoreload functionalities.
c.InteractiveShellApp.extensions = ['autoreload', 'pylab']
c.InteractiveShellApp.exec_lines = ['%autoreload 2', '%pylab']
If you are user of Anaconda and Spyder then best solution for you is that :
Tools
-->
Preferences
-->
Ipython console
-->
Graphic Section
Then in the Support for graphics (Matplotlib) section:
select two avaliable options
and in the Graphics Backend:
select Automatic
Another possibility when using easy_install is that you need to require the most recent version of matplotlib.
Try:
import pkg_resources
pkg_resources.require("matplotlib")
before you import matplotlib or any of its modules.

Categories