Python Matplotlib + Tkinter. Matplotlib reverts to "agg" backend because it can't find a valid display


I am using python and poetry, provided by NixOS to install a poetry virtual environment (no poetry2nix here).

I have set the matplotlib backend to “TkAgg” using the “MPLBACKEND” env var.

But when I try to plot something, the backend reverts to “agg”. I have traced the cause to the misidentificaiton of a headless session, which causes mpl to fallback to “agg” as the backend. The relevant clause is here:

I can force matplotlib to use “TkAgg” with matplotlib.use("TkAgg"), however this solution isn’t tenable for shared projects.

I assume that this .display_is_valid() method is returning headless because it can’t find some Wayland or X11 libraries it’s expecting to find. But would appreciate any pointers regarding how I can resolve this.

Many thanks for any help.

For anyone else facing similar issues - I resolved this by adding the X11 library to the LD_LIBRARY_PATH of my development shell. I am using X11, not sure if this works for WAYLAND.

      devShells."x86_64-linux".default = pkgs.mkShell {

        buildInputs = [ pkgs.python3Full pkgs.poetry ];

            (pkgs.lib.makeLibraryPath [
              pkgs.zlib # numpy
              pkgs.xorg.libX11 # matplotlib
        MPLBACKEND = "TkAgg";