Matplotlib plot is not displayed in window

Problem

I created a plot using the Matplotlib library in a Python script. But the call to show does not display the plot in a GUI window.

Solution

The rendering of a plot to a file or display is controlled by the backend that is set in Matplotlib. You can check the current backend using:

import matplotlib
matplotlib.get_backend()

I got the default backend as Agg. The possible values for GUI backends on Linux are Qt4Agg, GTKAgg, WXagg, TKAgg and GTK3Agg. Since Agg is not a GUI backend, nothing is being displayed.

I wanted to use the simple Tcl-Tk backend. So, I installed the necessary packages for Python:

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

The backend is not set automatically after this. In my Python script, I set it explicitly:

import matplotlib
matplotlib.rcParams["backend"] = "TkAgg"

The plot was displayed after this change.

However, this needs to be set immediately after the import line of Matplotlib and before importing matplotlib.pyplot. Doing this in the import region of a Python script is quite ugly.

Instead, I like to switch the backend of the matplotlib.pyplot object itself:

import matplotlib.pyplot as mplot
mplot.switch_backend("TkAgg")

This too worked fine for me! 🙂

Reference: Matplotlib figures not showing up or displaying

Tried with: Ubuntu 14.04

Advertisements

One thought on “Matplotlib plot is not displayed in window

  1. Thanx for this. It was useful. I built a Python 2.7.14 environment on a couple of older Linux laptops, and I had to explicitly set the backend parameter to use “TkAgg”, after importing _tkinter and matplotlib. I built Python from source, and Tck/Tk 8.5 as well. The matplotlib backend was defaulting to using ‘agg’, which meant I could only see images using IPython Notebooks. But with the your example of setting it explicitly here, I was able to get my Fedora Linux stuff to work right, and show a modified image, directly on the Gnome desktop. Works nice.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s