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 withpythonw
instead ofpython
- use
TKAgg
backend
Using the first one works well but I wonder:
- why do we need to call
pythonw
instead ofpython
? - 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)?