【发布时间】:2019-08-13 11:10:02
【问题描述】:
在 MacOS 上使用matplotlib 的问题是一个棘手的问题,许多讨论已经对它进行了彻底的审查(见下文)。问题如下:
- 使用 MacOS Mojave 10.14.3
- 在 conda 环境中使用 python 3.7.2
- 使用 matplotlib 3.0.3
这是我想出的最简单的代码 sn-p,它允许重现问题:
from matplotlib import pyplot as plt
x = [1, 2, 3]
y = [1, 2, 3]
plt.plot(x, y)
plt.show()
这会引发以下错误:
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)
该问题已记录在 here。一种解决方案是将PyQt5 包安装到您的Python 安装中,并在脚本的开头添加以下行:
import matplotlib
matplotlib.use("Qt5Agg")
虽然这很好用,但我想知道为什么其他后端无法提供类似的行为。
我确实尝试过使用 MacOSX 后端:
import matplotlib
matplotlib.use('MACOSX')
这会导致错误:
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.
该问题记录在 here、there 和 plenty of other threads 中。
两个解决方案出来了:
- 安装
python.app(conda install python.app) 并使用pythonw而不是python启动您的脚本 - 使用
TKAggbackend
使用第一个效果很好,但我想知道:
- 为什么我们需要调用
pythonw而不是python? -
python.app包到底是什么? - 我们如何使用 IDE(例如 PyCharm)使这个解决方案工作?
至于第二个,它确实“工作”到了一定程度:当使用TkAgg 运行matplotlib 时,绘图窗口确实有问题。实际上,它通常需要多次点击“缩放”、“平移”或“主页”按钮才能让它们真正工作。使用它真的很痛苦。我问了几个使用matplotlib 和TkAgg 的同事或朋友,他们都有同样的问题。
有人知道这种情况的原因吗?或者是否有任何解决方法可以避免这个问题(除了安装 pyqt5)?
【问题讨论】:
标签: python macos matplotlib