Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to install a GUI backend for matplotlib?

I have been struggling to get plot using matplotlib.pyplot. Obviously, the problem is

temp.py:58: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
  plt.show()

I realised that there are multiple backends to switch to, and 's snippet helped me list all inactive GUI backends.

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

To which I got

testing GTK3Agg
     GTK3Agg Not found
testing GTK3Cairo
     GTK3Cairo Not found
testing MacOSX
     MacOSX Not found
testing nbAgg
     nbAgg Not found
testing Qt4Agg
     Qt4Agg Not found
testing Qt4Cairo
     Qt4Cairo Not found
testing Qt5Agg
     Qt5Agg Not found
testing Qt5Cairo
     Qt5Cairo Not found
testing TkAgg
     TkAgg Not found
testing TkCairo
     TkCairo Not found
testing WebAgg
     WebAgg Not found
testing WX
     WX Not found
testing WXAgg
     WXAgg Not found
testing WXCairo
     WXCairo Not found

Some methods to setup a GUI backend suggest reinstalling python after installing some dependencies but I am looking for a simpler method (if any exists) .

like image 804
Pe Dro Avatar asked Oct 28 '25 08:10

Pe Dro


1 Answers

I went across methods and found the simplest method: Use TkAgg backend.

  1. Install tkinter
$ sudo apt-get install python-tk
$ sudo apt-get install python3-tk
  1. Specify this backend in your Python script
import matplotlib
matplotlib.use('TkAgg', force=True)
import matplotlib.pyplot as plt

Now you can freely call plt.show() for your plots and stay happy :)

like image 66
Pe Dro Avatar answered Oct 29 '25 23:10

Pe Dro