如何在 matplotlib/Python 中更改后端

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3285193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:24:56  来源:igfitidea点击:

How to change backends in matplotlib / Python

pythonmatplotlibbackendcairo

提问by DrDee

I am struggling with the following issue. I need to generate reports that consists of a collection of charts. All these charts, except one, are made using Matplotlib default backend (TkAgg). One chart needs to be made using the Cairo backend, the reason is that I am plotting an igraph graph and that can only be plotted using Cairo.

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

The issue is that I cannot change backends on the fly, for example the following does not work:
matplotlib.pyplot.switch_backend('cairo.png')(I know that the switch_backend functionality is experimental)

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

and I have also tried matplotlib.use("cairo.png")but this leads to import problems as the matplotlib.use("cairo.png")statement should come before importing matplotlib.pyplot. but I need two different backends over the course of the life of the script.

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

So my question is does someone have a code snippet that shows how to switch the backend in Matplotlib?

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

Thanks so much!

非常感谢!

UPDATE: I have written a snippet that loads matplotlib, shows the default backend, unloads matplotlib, reloads it and changes the backend:

更新:我编写了一个加载 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()

but is this really the way to do it?

但这真的是方法吗?

UPDATE 2: I had some serious brain freeze yesterday... The simple and most obvious solution is to use the Cairo backend for all charts and not to switch the backend at all :)

更新 2:昨天我有一些严重的大脑冻结......简单和最明显的解决方案是对所有图表使用开罗后端,而不是根本不切换后端:)

UPDATE 3: Actually, it's still an issue so anybody who knows how to dynamically switch matplotlib backends....please post your answer.

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

回答by helperfunction

So I am not completely sure if this is what you are looking for.

所以我不完全确定这是否是你正在寻找的。

You can change your backend through the matplotlibrc file which contains certain configurations for your matplotlib.

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

In your script you can put:

在您的脚本中,您可以输入:

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

or something like that to switch between backends.

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

回答by Ken Arnold

You could also have a different Python process make that plot, possibly with the help of pickle or joblib.

您也可以使用不同的 Python 进程来制作该图,可能在 pickle 或joblib的帮助下。

回答by oyo

There is an "experimental" feature :

有一个“实验性”功能:

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

taken from matplotlib doc.

取自matplotlib 文档

Switch the default backend to newbackend. This feature is experimental, and is only expected to work switching to an image backend. Eg, if you have a bunch of PostScript scripts that you want to run from an interactive ipython session, you may want to switch to the PS backend before running them to avoid having a bunch of GUI windows popup. If you try to interactively switch from one GUI backend to another, you will explode. Calling this command will close all open windows.

将默认后端切换为 newbackend。此功能是 实验性的,预计只能切换到图像后端。例如,如果您想从交互式 ipython 会话中运行一堆 PostScript 脚本,您可能希望在运行它们之前切换到 PS 后端,以避免弹出一堆 GUI 窗口。如果您尝试以交互方式从一个 GUI 后端切换到另一个,您将会爆炸。调用此命令将关闭所有打开的窗口。

回答by fredbaba

Why not just use the reloadbuilt-in function (importlib.reloadin Python 3)?

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

import matplotlib
matplotlib.use('agg')

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

回答by Rolf of Saxony

Six years later and I came across a similar issue, when trying to decide which backendwas available to use.
This code snippet works well for me:

六年后,当我试图决定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

As you can deduce, swapping the backendis as simple as re-importing matplotlib.pyplotafter forcing the new backend

正如您可以推断出的,交换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

For those still having trouble, this code will print out the:
list of Non Gui backends;
the list of Gui backends;
and then attempt to use each Gui backend to see if it is present and functioning.

对于那些仍然有问题的人,此代码将打印出:
非 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")

回答by Pe Dro

In my case (Windows 10 + python 3.7), the first answer by @Rolf of Saxony didn't work very well. Instead of trying all the available environments and configuring one of them at the beginning, i.e, just after

就我而言(Windows 10 + python 3.7),萨克森州@Rolf 的第一个答案效果不佳。而不是一开始就尝试所有可用的环境并配置其中一个,即,就在之后

    import matplotlib

I had to change the environment from 'Agg' to 'TkAgg' using

我不得不使用以下命令将环境从“Agg”更改为“TkAgg”

    matplotlib.use('TKAgg',warn=False, force=True)

right before the code where I actually plotted, i.e,

就在我实际绘制的代码之前,即

    import matplotlib.pyplot as plt
    fig = plt.figure()
    # AND SO ON....

回答by seralouk

To permanently change the backend you can use this:

要永久更改后端,您可以使用:

  1. First locate the matplotlibrcfile:

    import matplotlib
    
    matplotlib.matplotlib_fname()
    # '/Users/serafeim/.matplotlib/matplotlibrc'
    
  2. Open the terminaland do:

    cd /Users/serafeim/.matplotlib/
    ls
    
  3. Edit the file (if it does not exist use this command: touch matplotlibto create it):

    vim matplotlibrc
    
  4. Add this line and save:

    backend: TkAgg
    
  1. 首先找到matplotlibrc文件:

    import matplotlib
    
    matplotlib.matplotlib_fname()
    # '/Users/serafeim/.matplotlib/matplotlibrc'
    
  2. 打开终端并执行:

    cd /Users/serafeim/.matplotlib/
    ls
    
  3. 编辑文件(如果它不存在,请使用以下命令:touch matplotlib创建它):

    vim matplotlibrc
    
  4. 添加这一行并保存:

    backend: TkAgg