如何在matplotlib / Python中切换后端

我正在努力解决以下问题。 我需要生成由一组图表组成的报表。 所有这些图表,除了一个,都使用Matplotlib默认后端(TkAgg)。 一张图需要使用开罗后端,原因是我正在绘制igraph图,只能使用开罗绘制。

问题是我不能dynamic更改后端,例如以下不起作用:
matplotlib.pyplot.switch_backend('cairo.png') (我知道switch_backendfunction是实验性的)

我也试过matplotlib.use("cairo.png")但是这会导致导入问题,因为matplotlib.use("cairo.png")语句应该在导入matplotlib.pyplot之前出现。 但在脚本的生命周期中,我需要两个不同的后端。

所以我的问题是有人有一个代码片段,显示如何切换在Matplotlib后端?

非常感谢!

更新:我写了一个代码加载matplotlib,显示默认后端,卸载matplotlib,重新加载它,并更改后端:

 import matplotlib import matplotlib.pyplot as plt import sys print matplotlib.pyplot.get_backend() modules = [] for module in sys.modules: if module.startswith('matplotlib'): modules.append(module) for module in modules: sys.modules.pop(module) import matplotlib matplotlib.use("cairo.png") import matplotlib.pyplot as plt print matplotlib.pyplot.get_backend() 

但这真的是这样做的方式吗?

更新2:昨天我有一些严重的脑冻结…简单而最明显的解决scheme是使用开罗后端的所有图表,而不是切换后端所有:)

更新3:其实,这仍然是一个问题,所以谁知道如何dynamic地切换matplotlib后端….请发表您的答案。

有一个“实验性”function:

 import matplotlib.pyplot as p p.switch_backend('newbackend') 

取自matplotlib文件 。

将默认后端切换到newbackend。 这个function是实验性的 ,只能用于切换到图像后端。 例如,如果您想要从交互式ipython会话运行一堆PostScript脚本,则可能需要在运行它们之前切换到PS后端,以避免出现一堆GUI窗口。 如果您尝试从一个GUI后端交互切换到另一个,则会爆炸。 调用这个命令将closures所有打开的窗口。

为什么不使用reload内置函数(Python 3中的importlib.reload )?

 import matplotlib matplotlib.use('agg') matplotlib = reload(matplotlib) matplotlib.use('cairo.png') 

六年后,当我试图决定哪个backend可用时,我遇到了类似的问题。
这段代码适合我:

 import matplotlib gui_env = ['TKAgg','GTKAgg','Qt4Agg','WXAgg'] for gui in gui_env: try: print "testing", gui matplotlib.use(gui,warn=False, force=True) from matplotlib import pyplot as plt break except: continue print "Using:",matplotlib.get_backend() Using: GTKAgg 

正如你所推论的,交换backend就像在强制新的backend之后重新导入matplotlib.pyplot一样简单

 matplotlib.use('WXAgg',warn=False, force=True) from matplotlib import pyplot as plt print "Switched to:",matplotlib.get_backend() Switched to: WXAgg 

对于那些仍然有麻烦,这个代码将打印出:
Non Gui后端名单
Gui后端列表;
然后尝试使用每个Gui后端来查看它是否存在并运行。

 import matplotlib gui_env = [i for i in matplotlib.rcsetup.interactive_bk] non_gui_backends = matplotlib.rcsetup.non_interactive_bk print ("Non Gui backends are:", non_gui_backends) print ("Gui backends I will test for", gui_env) for gui in gui_env: print ("testing", gui) try: matplotlib.use(gui,warn=False, force=True) from matplotlib import pyplot as plt print (" ",gui, "Is Available") plt.plot([1.5,2.0,2.5]) fig = plt.gcf() fig.suptitle(gui) plt.show() print ("Using ..... ",matplotlib.get_backend()) except: print (" ",gui, "Not found") 

你也可以有一个不同的Python进程来制作这个剧情,可能还有pickle或joblib的帮助。

所以我不完全确定,如果这是你在找什么。

您可以通过matplotlibrc文件更改您的后端,该文件包含matplotlib的某些configuration。

在你的脚本中你可以放:

 matplotlib.rcParams['backend'] = 'TkAgg' 

或类似的东西在后端之间切换。