~couchNerd ~serialOutrager ~puts2In42 ~makesPigsFly

Fixing the problem of matplotlib and ggplot not showing graphs in python

· by Shantanu Goel · Read in about 2 min · (253 Words)
ggplot graphs matplotlib python

While trying to make some graphs for one of my side projects recently, I came across an issue that both matplotlib and ggplot did not show up the graphs. I was able to save the graphs to an image file just fine, but if I tried to show them directly on screen while running the script, it just printed a number and exited. After tearing apart my hair for some time, I checked the backend being used by matplot lib:

import matplotlib matplotlib.get_backend()

And there was the problem. It showed the backend being used was “agg”. Looking at the matplotlib documentation, I figured that this backend is used for rendering the graph into an image and saving it. That explained why I was able to save the images fine. But it didn’t have any interactive support. For that I had to install one of the other backends which had this support, e.g., Tkagg. So, for that what I had to do was, first install the Tk related packages using the below command:

sudo apt-get install tcl-dev tk-dev python-tk python3-tk

Another important step now is to reinstall matplotlib so that it detects the new backend, but also remember that if you just do a plain pip uninstall/install, it may not work because that will pick up the previous cached installation. So you have to use the –no-cache-dir option like below:

pip uninstall matplotlib pip install matplotlib --no-cache-dir

Now, the graphs work fine for both saving as image as well as showing up during runtime.