Subject: Re: bug#70687: python-matplotlib not respecting env var MPLBACKEND=TkAgg

From: Liliana Marie Prikler <[email-masked]>
Date: Sun, 06 Apr 2025 01:00:44 +0200

Hi Jake,

Am Donnerstag, dem 03.04.2025 um 11:36 +0000 schrieb Jake:
> It appears that importing matplotlib.pyplot resets the Matplotlib
> backend to Agg.
> 
>   $ guix shell python python-matplotlib -- bash -c 'MPLBACKEND=tkagg
> python3 -c "import matplotlib; print(matplotlib.get_backend());
> import matplotlib.pyplot; print(matplotlib.get_backend())"'
> 
>   TkAgg
>   agg
I recently encountered the same issue.  The issue is that matplotlib
internally sources a configuration file that sets the backend *after*
reading the environment variable.  To circumvent this, you use
something along the lines of the following code until the issue is
fixed:

  from matplotlib import set_backend 
  from os import environ
  
  […]

  if __name__ == '__main__':
    if 'MPLBACKEND' in environ: set_backend(environ['MPLBACKEND'])
    […]

Cheers