我正在努力解决以下问题。我需要生成包含图表集合的报告。除一个图表外,所有这些图表都是使用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后端的人都可以。...请发表您的答案。
六年后,当我试图确定可以使用哪个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")
[具有“实验性”功能:
为什么不只使用reload
内置函数(Python 3中为reload
)?
所以我不确定您是否正在寻找这个。
要永久更改后端,您可以使用此:
您也可能有其他的Python程序来制作该图,可能是通过pickle或vim matplotlibrc
来进行。
在我的情况下(Windows 10 + python 3.7),萨克森州@Rolf的第一个回答效果不佳。无需尝试所有可用环境并在一开始就配置其中一个,即,就在