Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change backends in matplotlib / Python

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.

like image 748
DrDee Avatar asked Jul 19 '10 21:07

DrDee


People also ask

What is matplotlib use (' AGG ')?

Matplotlib is a plotting library. It relies on some backend to actually render the plots. The default backend is the agg backend. This backend only renders PNGs. On Jupyter notebooks the matplotlib backends are special as they are rendered to the browser.

How do I change the plot style in matplotlib?

Another way to change the visual appearance of plots is to set the rcParams in a so-called style sheet and import that style sheet with matplotlib. style. use . In this way you can switch easily between different styles by simply changing the imported style sheet.


1 Answers

Six years later and I came across a similar issue, when trying to decide which backend was available to use.
Note see Caveats - below

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

Caveats: Changes in matplotlib since version 3.3.0

  • The first parameter of matplotlib.use has been renamed from arg to backend (only relevant if you pass by keyword).
  • The parameter warn of matplotlib.use has been removed. A failure to switch the backend will now always raise an ImportError if force is set; catch that error if necessary.
  • All parameters of matplotlib.use except the first one are now keyword-only.
like image 60
Rolf of Saxony Avatar answered Sep 20 '22 13:09

Rolf of Saxony