所有可用的matplotlib后端列表
现在的后台名称可以通过
>>> import matplotlib.pyplot as plt >>> plt.get_backend() 'GTKAgg'
有没有办法获取某台机器上所有可以使用的后台列表呢?
7 个回答
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']
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)
62
你可以访问这些列表
matplotlib.rcsetup.interactive_bk
matplotlib.rcsetup.non_interactive_bk
matplotlib.rcsetup.all_backends
第三个列表是前两个列表的合并。如果我没看错源代码,这些列表是写死在代码里的,并不能告诉你哪些后端实际上是可以用的。还有一个
matplotlib.rcsetup.validate_backend(name)
但这个也只是检查了那个写死的列表。