How to change backends in matplotlib / Python

给你一囗甜甜゛ 提交于 2019-11-26 02:08:18

问题


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.

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)

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.

So my question is does someone have a code snippet that shows how to switch the backend in 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:

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

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


回答1:


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

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 backend is as simple as re-importing matplotlib.pyplot after forcing the new 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.

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



回答2:


There is an "experimental" feature :

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

taken from matplotlib doc.

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.




回答3:


Why not just use the reload built-in function (importlib.reload in Python 3)?

import matplotlib
matplotlib.use('agg')

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



回答4:


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.

In your script you can put:

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

or something like that to switch between backends.




回答5:


To permanently change the backend you can use this:

  1. First locate the matplotlibrc file:

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

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

    vim matplotlibrc
    
  4. Add this line and save:

    backend: TkAgg
    



回答6:


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




回答7:


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

    import matplotlib

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

    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....


来源:https://stackoverflow.com/questions/3285193/how-to-change-backends-in-matplotlib-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!