【问题标题】:Is there a way to automatically switch matplotlib backend in Jupyter?有没有办法在 Jupyter 中自动切换 matplotlib 后端?
【发布时间】:2020-06-01 10:35:56
【问题描述】:

在使用我的 python 包时,某个函数会执行一些交互式 matplotlib 内容。 在 Jupyter Notebook 中,我总是必须使用魔法 %matplotlib qt 来切换后端以使其正常工作。 然而,这对我来说似乎很明显,但其他尝试使用我的包的人并不是那么简单。

这是我目前在__init__.py 中的内容:

def run_from_notebook():
    return hasattr(__builtins__, '__IPYTHON__')

if run_from_notebook():
     # this has no effect
    try:
        from IPython import get_ipython
        ipython = get_ipython()
    except ImportError:
        import IPython.ipapi
        ipython = IPython.ipapi.get()

    ipython.magic("matplotlib qt") 

我也试过了:

if matplotlib.get_backend() != 'Qt5Agg':
    matplotlib.use('Qt5Agg')

但仍然没有效果。

当有人导入我的包时,有没有办法在 Jupyter Notebook 中自动切换后端? 还有:有什么理由不被认为是一种好的做法?

【问题讨论】:

  • switch_backend 有帮助吗?
  • @jayveesea 不幸的是,它没有。

标签: python matplotlib jupyter-notebook jupyter


【解决方案1】:

原来问题出在run_from_notebook 函数上。当它只是在笔记本单元中运行时,它返回True,但是当它从我的模块中导入时,它返回False。现在的问题是:如何检测代码是否在 Jupyter 中运行?

例如手动运行

def switch_backend_to_Qt5():
    import matplotlib
    if matplotlib.get_backend() != 'Qt5Agg':
        matplotlib.use('Qt5Agg')

完成工作。

编辑:

以下功能适合我的需要:

import os

def run_from_notebook():
    try:
        __IPYTHON__
        #  If it's run inside Spyder we don't need to do anything
        if any('SPYDER' in name for name in os.environ):
            return False
        # else it's probably necessary to switch backend
        return True
    except NameError:
        return False

【讨论】:

  • 更多解决方案here 用于检查是否在笔记本中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
  • 1970-01-01
  • 2011-03-31
  • 1970-01-01
  • 1970-01-01
  • 2012-02-15
  • 1970-01-01
相关资源
最近更新 更多