小编典典

如何在matplotlib / Python中更改后端

python

我正在努力解决以下问题。我需要生成包含图表集合的报告。除一个图表外,所有这些图表都是使用Matplotlib默认后端(TkAgg)制作的。需要使用Cairo后端制作一张图表,原因是我正在绘制igraph图形,并且只能使用Cairo绘制。

问题是我无法即时更改后端,例如以下操作不起作用:(
matplotlib.pyplot.switch_backend(‘cairo.png’) 我知道switch_backend功能是实验性的)

而且我也尝试过,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:昨天我有一些严重的大脑冻结……最简单,最明显的解决方案是对所有图表使用开罗后端,而根本不切换后端:)

更新3:实际上,这仍然是一个问题,所以任何知道如何动态切换matplotlib后端的人..请发表您的答案。


阅读 353

收藏
2021-01-20

共1个答案

小编典典

六年后,当我尝试确定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就像matplotlib.pyplot强制新文件后重新导入一样简单backend

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")

注意事项:自3.3.0版以来,matplotlib发生了变化

  • matplotlib.use的第一个参数已从arg重命名为backend(仅在通过关键字传递时才相关)。
  • matplotlib.use的参数警告已删除。现在,如果设置了强制,切换后端失败将始终引发ImportError;必要时捕获该错误。
  • 现在,除第一个参数外,matplotlib.use的所有参数仅是关键字。
2021-01-20