所有可用的matplotlib后端列表

81

当前的后端名称可以通过以下方式访问:

>>> import matplotlib.pyplot as plt
>>> plt.get_backend()
'GTKAgg'

有没有一种方法可以获取可以在特定计算机上使用的所有后端的列表?


FYI,从 matplotlib 版本 3.x 开始,默认的 pip 安装不会安装交互式后端,因此您需要安装其中一个交互式后端,例如 PyQt4PyQt5。请参阅 https://matplotlib.org/3.3.3/users/installing.html#install-requirements 以获取有关支持的交互式后端的更多信息。 - Trevor Boyd Smith
7个回答

62

你可以访问这些列表

matplotlib.rcsetup.interactive_bk
matplotlib.rcsetup.non_interactive_bk
matplotlib.rcsetup.all_backends

第三个列表是前两个列表连接而成的。如果我正确地阅读了源代码,那么这些列表虽然是硬编码的,但并不能告诉你实际可用的后端。此外还有

matplotlib.rcsetup.validate_backend(name)

但这种方法仅仅是针对硬编码列表进行检查。


53

这是之前发布的脚本的修改版。它找到所有支持的后端,验证它们并测量它们的fps。在OSX上,当涉及到tkAgg时,它会导致Python崩溃,所以请自行决定是否使用;)

from __future__ import print_function, division, absolute_import
from pylab import *
import time

import matplotlib.backends
import matplotlib.pyplot as p
import os.path


def is_backend_module(fname):
    """Identifies if a filename is a matplotlib backend module"""
    return fname.startswith('backend_') and fname.endswith('.py')

def backend_fname_formatter(fname): 
    """Removes the extension of the given filename, then takes away the leading 'backend_'."""
    return os.path.splitext(fname)[0][8:]

# get the directory where the backends live
backends_dir = os.path.dirname(matplotlib.backends.__file__)

# filter all files in that directory to identify all files which provide a backend
backend_fnames = filter(is_backend_module, os.listdir(backends_dir))

backends = [backend_fname_formatter(fname) for fname in backend_fnames]

print("supported backends: \t" + str(backends))

# validate backends
backends_valid = []
for b in backends:
    try:
        p.switch_backend(b)
        backends_valid += [b]
    except:
        continue

print("valid backends: \t" + str(backends_valid))


# try backends performance
for b in backends_valid:

    ion()
    try:
        p.switch_backend(b)


        clf()
        tstart = time.time()               # for profiling
        x = arange(0,2*pi,0.01)            # x-array
        line, = plot(x,sin(x))
        for i in arange(1,200):
            line.set_ydata(sin(x+i/10.0))  # update the data
            draw()                         # redraw the canvas

        print(b + ' FPS: \t' , 200/(time.time()-tstart))
        ioff()

    except:
        print(b + " error :(")

要查看支持的交互式后端,请参见:

#!/usr/bin/env python
from __future__ import print_function
import matplotlib.pyplot as plt
import matplotlib

backends = matplotlib.rcsetup.interactive_bk
# validate backends
backends_valid = []
for b in backends:
    try:
        plt.switch_backend(b)
        backends_valid += [b]
    except:
        continue
print(backends_valid)

这个脚本在我的电脑上崩溃了(https://gist.github.com/palmstrom/6039823),但在Spyder IDE下运行良好。 - Matěj Šmíd
这个基准测试的典型结果是什么?有人有FPS数字吗? - rc0r
2
太棒了!实时绘图!计算帧率并打印出来!非常有用,可以弄清楚哪个后端在您的机器上最快。 - Trevor Boyd Smith
1
要在python2下运行脚本,请将shebang后的第一行改为from __future__ import print_function, division, absolute_import。(我原本想编辑问题中的代码...但是python2现在太老了...我觉得添加这种东西是不好的行为...我感觉这只会鼓励不良行为。) - Trevor Boyd Smith
不错的片段!尽管不鼓励使用"from pylab import *",可以参考这个链接:(https://matplotlib.org/stable/api/pylab.html)。 - undefined

8
您可以假装输入错误的后端参数,然后它会返回一个ValueError,其中包含有效的matplotlib后端列表,例如:

输入:

import matplotlib
matplotlib.use('WRONG_ARG')

输出:

ValueError: Unrecognized backend string 'test': valid strings are ['GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nbAgg', 'Qt4Agg', 'Qt4Cairo', 'Qt5Agg', 'Qt
5Cairo', 'TkAgg', 'TkCairo', 'WebAgg', 'WX', 'WXAgg', 'WXCairo', 'agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template']

6

在Sven提到的硬编码列表中,可以找到Matplotlib可以使用的每个后端(基于当前设置后端的实现),可以检查matplotlib/backends文件夹。

以下代码可以实现此功能:

import matplotlib.backends
import os.path

def is_backend_module(fname):
    """Identifies if a filename is a matplotlib backend module"""
    return fname.startswith('backend_') and fname.endswith('.py')

def backend_fname_formatter(fname): 
    """Removes the extension of the given filename, then takes away the leading 'backend_'."""
    return os.path.splitext(fname)[0][8:]

# get the directory where the backends live
backends_dir = os.path.dirname(matplotlib.backends.__file__)

# filter all files in that directory to identify all files which provide a backend
backend_fnames = filter(is_backend_module, os.listdir(backends_dir))

backends = [backend_fname_formatter(fname) for fname in backend_fnames]

print backends

4

您还可以在此处查看一些后端的文档:

http://matplotlib.org/api/index_backend_api.html

该页面列出了一些后端,其中一些没有适当的文档:
matplotlib.backend_bases
matplotlib.backends.backend_gtkagg
matplotlib.backends.backend_qt4agg
matplotlib.backends.backend_wxagg
matplotlib.backends.backend_pdf
matplotlib.dviread
matplotlib.type1font

对不起,我以为上面的回答已经涵盖了这个主题,但应该提供链接作为参考,这就是我发帖的原因。我的意思并不是有恶意,我是一个新手。 - Leandro

4

这个怎么样?

%matplotlib --list
Available matplotlib backends: ['tk', 'gtk', 'gtk3', 'wx', 'qt4', 'qt5', 'qt', 'osx', 'nbagg', 'notebook', 'agg', 'svg', 'pdf', 'ps', 'inline', 'ipympl', 'widget']

2
您可以查看以下文件夹,以获取可能的后端列表...
/Library/Python/2.6/site-packages/matplotlib/backends
/usr/lib64/Python2.6/site-packages/matplotlib/backends

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接