matplotlib example code not working on python virtual environment - python

I am trying to display the x y z coordinate of an image in matplotlib. the example code work perfectly well on the global python installation: As I move the cursor the x,y,z values get updated instantaneously. However, when I run the example code on a python virtual environment, I would click on the images several times for the coordinate to show in the first place, then when I click on different positions it would update for some. After few clicks, the coordinates will no longer update.
I don't know how to debug this.

This is likely to be a problem with the macosx backend for matplotlib. Switch to using an alternative backend for matplotlib (e.g. use qt4 instead of 'macosx'). For details of how to switch backend and what exactly that means - see the docs here. Note that you might have to install the backend first - e.g. pyqt to use the qt4agg backend as I'm suggesting here.
In summary - the backend deals with the output from matplotlib and matplotlib can target different output formats. These can be gui display output formats (for instance wx, qt4 and so on), or file outputs (for instance pdf). These are known as interactive and non-interactive backends respectively.
To change backend either do
import matplotlib
matplotlib.use('qt4agg')
in code, or - if you want to change for every time you start matplotlib - edit your matplotlibrc file setting the backend attribute e.g.
backend: Qt4Agg
N.B. I was alerted by a comment that since posting this answer, matplotlib docs now refer to this issue and suggest a workaround, although the commenter noted that the solution offered in this answer (switch to Qt backend) worked for them where the official docs workaround was not possible for them.

What finally worked for me was to make a local matplotlibrc file containing the directive: backend: TkAgg.
# Within working directory where running python
vim matplotlibrc
# new file via vim, Nano, whatever
backend: TkAgg
This was useful:
import matplotlib
print matplotlib.rcParams['backend']
Other Notes:
I had also installed pyqt using Homebrew (brew install pyqt) and copied (could just move it) into $MyVirtEnv/lib/python2.7/site-packages/ from /usr/local/lib/python2.7/site-packages/PyQt4
But when I
import matplotlib
matplotlib.use('qt4Agg')
import librosa
"Matplotlib qt-based backends require an external PyQt4, PyQt5,\n"
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5,
or PySide package to be installed, but it was not found.
Had also tried
pip install pyside
Successfully installed pyside-1.2.4
Same error
>>> import pyside
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pyside
Also got the following error at some point when trying to reimport matplotlib (i think).
from . import cache
ImportError: cannot import name cache

As pointed out in Matplotlib virtualenv FAQ, vext is the solution here.
It allows to use the system-wide pyqt5 for instance.
This is necessary until PyQt5 setup knows about virtualenvs:
pip3 install vext.pyqt5

Just add plt.show() at the end and the problem was solved for me.

Related

Matplotlib has a problem finding a backend after I use pyinstaller

I'm trying to make an .exe file from .py and I'm having an issue with matplotlib library. When I run my script in VS Code plt.show() works just fine. But when I use pyinstaller to make an .exe and run the .exe file, it gives me a following warning: "UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." Importing TkAgg directly with "import matplotlib.backends.backend_tkagg" doesn't solve the problem either.
Is it possible to fix that?
I ran into the same issue.
I found this article, which may be helpful:
"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm
However, the simple fix in my case was to just explicitly import the backend module(s):
import matplotlib.backends.backend_tkagg
import matplotlib.backends.backend_wxagg
Pyinstaller does some relatively sophisticated analysis and Matplotlib itself has some relatively sophisticated code to be able to use multiple GUI backends. I think the overall problem is that Pyinstaller isn't seeing that any particular backend is actually being used and so doesn't end up bundling any backend module.
Explicitly making the import makes it obvious to Pyinstaller that you want that module (importing it is effectively using it). (Maybe you only need the one for 'tkagg' - I happen to be working with a WX GUI, so I included both imports - it works.)

Which backend for matplotlib using MacOS?

The question of using matplotlib with MacOS is a tricky one which has already been thoroughly reviewed by a number of discussions (see below). The problem is the following:
using MacOS Mojave 10.14.3
using python 3.7.2 in a conda environment
using matplotlib 3.0.3
Here is the simplest code snippet I came up with which allows reproducing the issue:
from matplotlib import pyplot as plt
x = [1, 2, 3]
y = [1, 2, 3]
plt.plot(x, y)
plt.show()
This throws the following error:
2019-03-22 12:25:43.429 python3.7[22209:554135] -[NSApplication _setup:]: unrecognized selector sent to instance 0x7f85866b9de0
2019-03-22 12:25:43.431 python3.7[22209:554135] \*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSApplication _setup:]: unrecognized selector sent to instance 0x7f85866b9de0'
*** First throw call stack:([...])
libc++abi.dylib: terminating with uncaught exception of type NSException
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
The issue is documented here. One solution is to install the PyQt5 package to your Python installation and to add the following lines at the beginning of your script:
import matplotlib
matplotlib.use("Qt5Agg")
While this works perfectly well, I am wondering why other backends fail to provide similar behavior.
Indeed I tried using MacOSX backend :
import matplotlib
matplotlib.use('MACOSX')
Which yields to the error:
from matplotlib.backends import _macosx
ImportError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.
The issue is documented here, there and in plenty of other threads.
Two solutions came out :
install python.app(conda install python.app) and launch your script with pythonw instead of python
use TKAggbackend
Using the first one works well but I wonder:
why do we need to call pythonw instead of python ?
what exactly is the python.app package ?
how can we make this solution work using an IDE (let say PyCharm for instance) ?
As for the second one, it does "work" up to a certain point: when running matplotlib using TkAgg, the plot window is really buggy. Indeed, it often needs several clicks on the "zoom", "pan" or "home" buttons to get them to actually work. It really is a great pain to use it. I asked several colleagues or friends using matplotlib with TkAgg and they all have the same issue.
Does anyone know the reason for this state of fact? Or if there is any workaround to avoid this issue (apart from installing pyqt5)?
Using the first option is your best bet since you are already working with a virtual environment.
According to matplotlib, there are two variants of python:
A Framework build - Quite important for GUI stuffs in MacOXs
A regular build.
Matplotlib in this case would want to interact natively with OSX and for this, it needs the Framework build this is the reason why installing the python.app type of python is important.
More information can be gotten from Matplotlib FAQ.
Check this link for more about the need for a framework build python.
I'm going to make some assumptions. If they're wrong I apologize.
You installed Python with Anaconda.
Personally, I've never had any problems on mac with matplotlib. My setup is: Mojave, Python3.7.3 in a venv using the python built in module (python3 -m venv), and matplotlib 3.0.3.
I can't answer your question on how to fix your problem, but I'm kind of trying to answer your "is there any workaround" question. Personally, I've always had issues with using Anaconda/Spyder/Conda for Python. I've always felt installing it as its own binary/app on the system leads to the fewest errors.
Now, I'm not saying you have to download and install by hand though. I use homebrew and it saves me headaches everyday I assume (such as upgrading applications and packages). That's the "work around" I'd suggest. Because isn't installing via Anaconda/Spyder already a workaround to installing Python properly? I've always felt performing one work around requires more workarounds for full functionality. Such as having to specify the matplotlib backend when it should be detected by default.
Obviously, I'm a little biased against that tool and that may be reflected in this answer, so take it with a grain of salt. Even though Conda is a legitimate tool that I think is useful, I find it annoying having to use both pip and conda when conda doesn't contain the packages I want.
There are two things you can try.
You can read Matplotlib info page on that, https://matplotlib.org/3.1.0/faq/osx_framework.html,
The default python provided in (Ana)conda is not a framework build. However, a framework build can easily be installed, both in the main environment and in conda envs: install python.app (conda install python.app) and use pythonw rather than python.
And follow the instructions.
Or simply follow the error message you get when you try %matplotlib inline,
(...)
UnknownBackend: No event loop integration for 'inline'. Supported event loops are: qt, qt4, qt5, gtk, gtk2, gtk3, tk, wx, pyglet, glut, osx
I did %matplotlib osx and have plt.imshow(myimg) working just fine afterwards.

'module 'matplotlib' has no attribute 'pyplot''

When trying to import pyplot from matplotlib, I get this error (python 3.6). It works fine on my other computer, which has python 3.5, but I don't think it changed much.
I've tried both:
from matplotlib import pyplot as plt
and
import matplotlib.pyplot as plt
It's really annoying me that I can't figure this out.
matplotlib targets many different use cases and output formats. Some people use matplotlib interactively from the python shell and have plotting windows pop up when they type commands. Some people embed matplotlib into graphical user interfaces like wxpython or pygtk to build rich applications. Others use matplotlib in batch scripts to generate postscript images from some numerical simulations, and still others in web application servers to dynamically serve up graphs.
To support all of these use cases, matplotlib can target different outputs, and each of these capabilities is called a backend; the “frontend” is the user facing code, i.e., the plotting code, whereas the “backend” does all the hard work behind-the-scenes to make the figure. There are two types of backends: user interface backends (for use in pygtk, wxpython, tkinter, qt4, or macosx; also referred to as “interactive backends”) and hardcopy backends to make image files (PNG, SVG, PDF, PS; also referred to as “non-interactive backends”).
In yout case you have to choose backend "Agg" to use pyplot.
Solution:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
reference:
https://matplotlib.org/tutorials/introductory/usage.html#what-is-a-backend
https://github.com/matplotlib/matplotlib/issues/9954
Let me guess:
1:Maybe you have not properly installed matplotlib, you can try this:
pip3.6 install --upgrade matplotlib
Or just deleted the package and reinstall
2:Check whether you have use the same config environment and execution environment:
In some cases, you have installed packages for your local python interpreter, but you actually run your program on python virtual env. Maybe you have not properly installed the package on virtual env.

matplotlib does not import PyQt4, PyQt5 or PySide

I'm using Canopy 2.1.3 distribution (on Ubuntu 16.04) which as you may know contains the matplotlib package. Simply running in the Canopy's shell import matplotlib.pyplot as plt gives me
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5,
or PySide package to be installed, but it was not found.
I have installed all of the three packages with Synaptic but the problem persists.
Could this be related to environment variables? Or, could it be because Canopy's Python 3.5 and Ubuntu's Python 2.7 are conflicting?
EDIT:
I have finally used the PyQt by installing it from the Canopy's package manager.
It is likely that the default backend for matplotlib.pyplot is set to qt.
I have very little experience with canopy, but it should be possible to change the default to another back end; maybe someone else will be able to tell you how, or you can find it by yourself.
In the meantime, you can try to add this above all other matplotlib imports:
import matplotlib
matplotlib.use('TkAgg')
From the user guide:
Known Issue: In Canopy running Python 3, GUI backend must be explicitly set
If you ask matplotlib to display a plot, or otherwise run Python code that creates a GUI window, by default you will get an error traceback ending with: ImportError: No module named 'PyQt4'
The solutions are to install PyQt (which is GPL-licensed) in the Canopy Package Manager, or to use the Canopy Preference menu’s Python tab to specify the TK PyLab backend for creating GUIs. For details, see “Python 3 in Canopy 2 - ‘No module named PyQt4’ error”

plot window doesn't show - Tkinter present but header files are not found.

I have an application in python2.7 which runs fine.
Because i wanted to run it on a different laptop,i installed the matplotlib1.1 .
The problem is that the application finishes but no plot window exists.
Problem with Gtk or Tk? I tried to do in the matplotlibrc file "backend:TkAgg" or "GtkAgg" but still the same.
I forgot to mention that the laptop runs linux.
----------EDIT-------------------
I tried the installation again and it shows a message:
You may need to define display for tk to work so that setup can
determine where your libraries are located.Tkinter present but header
files are not found.
Some part of code:
import matplotlib.pyplot as plt
import scipy as sc
from matplotlib.animation import ArtistAnimation
...........
fig=plt.gcf()
ani=ArtistAnimation(fig,result,interval=10,repeat=False)
plt.show()
Even with TkAgg, matplotlib does not necessarily show the plot until you explicitly tell it to.
If you use pylab, you can explicitly cause it to show with something like this:
import pylab
pylab.plot([1,2,1,3])
pylab.show()
The call to show() will return when you close the window.
You can make it automatically show when you do a plot by writing
interactive: true
in your matplolibrc file. There is a system-wide config file in mpl-data/matplotlibrc in the installed packate. You have a personal config in ~/.matplotlib/matplotlibrc
Some systems seem to have interactive=true by default, others do not.
I found the answer here.
Finally!
(I have done manual install because it wanted the version 1.1)
I tried this :
sudo apt-get install python-pip
sudo pip install matplotlib

Categories

Resources