System-wide matplotlib backend selection depending on display availability

324 views Asked by At

Let's say we have a computer that we access either locally or remotely (both with X server forwarding [ssh -X] and without it ssh).

When using matplotlib we probably want to use a different backend depending on the kind of session we're in. Agg when there is no X server so we get plots and not exceptions, and TkAgg when there is so we can play a bit more with our plots.

But all these are static solutions, that work well if you always want to use the same backend (per computer, per user or even per script)

If you want the backend to be chosen in a given script depending on the availability X server, you can check the display at the beginning of the script and then load whichever backend you prefer. However, you need to insert this lines of code at the beggining of every script you want to run in both scenarios...

Is there any way to select the backend depending on the availability of a display but as a configuration that applies system-wide or user-wide, for any script that is run? I'm thinking of something like a default backend when there is display available and a fall-back backend when there is not, that applies without modifying the scripts (unless the scripts specifically select some backend). Is this possible?

1

There are 1 answers

0
Mark On

I would like matplotlib to have this fallback functionality as a setting somewhere, but I can't find anything.

So I made this script that you can put in .bashrc to fall back automatically if DISPLAY is not set.

You can adapt the backends to use with and without DISPLAY (replace TkAgg and Agg) and change the location of matplotlibrc (two places).

# create the settings file if it doesn't exist
cp -n /etc/matplotlibrc ~/.config/matplotlib/matplotlibrc
# set the backend to use depending on $DISPLAY
if [ -z "$DISPLAY" ]; then backend=Agg; else backend=TkAgg; fi
# find the line(s) starting with 'backend' and replaced them
sed -i "s/^backend.*/backend      : $backend/" ~/.config/matplotlib/matplotlibrc

This is particularly useful if you have a homedir that you use through ssh and through graphical interface (like the question); otherwise you can just create a static matplotlibrc.