Title: Resolved: Matplotlib figures not showing up or displaying - PyImageSearch

URL Source: https://pyimagesearch.com/2015/08/24/resolved-matplotlib-figures-not-showing-up-or-displaying/

Published Time: 2015-08-24T14:00:52+00:00

Markdown Content:
[![Image 1: matplotlib_osx_vs_ubuntu](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20241'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/07/matplotlib_osx_vs_ubuntu.jpg)

I think a better title for this blog post might be: _**How I lost a day of productivity to Ubuntu, virtual environments, matplotlib, and rendering backends.**_

Over the weekend I was playing around with deep learning on my Ubuntu system and went to plot the accuracy scores of my classifier. I coded up a quick Python script using [matplotlib](http://matplotlib.org/), executed the script, **only to not have the figure displayed to my screen**.

My script executed just fine. No error messages. No warnings. _**But there was still no plot to be found!**_

This is actually a common problem I’ve ran into over the past few months, _especially_ when working with Debian based operating systems such as Ubuntu and Raspbian. This issue is only further compounded when utilizing virtual environments via the [virtualenv](https://virtualenv.pypa.io/en/latest/) and [virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/) packages.

The issue actually stems from the [matplotlib backend](http://matplotlib.org/faq/usage_faq.html#what-is-a-backend) not being properly set, or from a missing dependency when compiling and installing matplotlib. Luckily, after a lot of trial and error (and spending an entire day trying to come up with a solution), I have been able to resolve the problem and get matplotlib figures to show up and display on my screen on both the Ubuntu and Raspbian operating systems (and when using Python virtual environments).

While this post is not exactly related to computer vision or OpenCV, I still want to share my experience and solution with other PyImageSearch readers. Matplotlib is a heavily used package in the Python scientific community and I hope that this article helps other readers resolve this strange and hard to pinpoint issue.

Setting the stage
-----------------

Let’s go ahead and set the stage.

*   We’re using a Debian based operating system such as Ubuntu or Raspbian.
*   We’re (optionally) utilizing Python virtual environments via virtualenv and virtualenvwrapper.
*   And our goal is to take the following image _(left)_ and compute a grayscale pixel intensity histogram for it using matplotlib _(right)_:

[![Image 2: Figure 1: Our end goal is to utilize matplotlib to display a grayscale pixel intensity for the image on the left.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20282'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/07/matplotlib_histogram_example.jpg)

**Figure 1:** Our end goal is to utilize matplotlib to display a grayscale pixel intensity for the image on the left.

Since we are using [matplotlib](http://matplotlib.org/), let’s create a new virtual environment called `plotting` :

$ mkvirtualenv plotting

Now that we’re in the `plotting` environment, let’s install `numpy` , `scipy` , and `matplotlib` :

$ pip install numpy
$ pip install scipy
$ pip install matplotlib

Awesome — all of our Python dependencies are installed. Now, let’s write a few lines of code to load the image, convert it to grayscale, compute a histogram over the grayscale image, and finally display it to our screen. I’ll throw all this code into a file named `grayscale_histogram.py` :

\# import the necessary packages
from matplotlib import pyplot as plt
import cv2

# load the image, convert it to grayscale, and show it
image = cv2.imread("raptors.jpg")
gray = cv2.cvtColor(image, cv2.COLOR\_BGR2GRAY)
cv2.imshow("Image", image)
cv2.imshow("Gray", gray)
cv2.waitKey(0)

# construct a grayscale histogram
hist = cv2.calcHist(\[gray\], \[0\], None, \[256\], \[0, 256\])

# plot the histogram
plt.figure()
plt.title("Grayscale Histogram")
plt.xlabel("Bins")
plt.ylabel("# of Pixels")
plt.plot(hist)
plt.xlim(\[0, 256\])
plt.show()
cv2.waitKey(0)

The code here is fairly straightforward. **Lines 1 and 2** import `matplotlib` and `cv2` . We then load our image and convert it to grayscale (**Lines 4-9**). From there the `cv2.calcHist` function is used to compute a histogram over the grayscale pixel intensities. Finally, **Lines 14-22** plot the histogram using `matplotlib` .

To execute our script, all we need to do is fire up and shell and issue the following command:

$ python grayscale\_histogram.py

When I execute the code on my OSX machine in the `plotting` virtual environment, the histogram is computed and both the grayscale image and histogram are displayed to my screen:

[![Image 3: Figure 2: Using OSX, I can successfully plot and display my grayscale histogram using matplotlib.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20375'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/07/matplotlib_osx_plotting.jpg)

**Figure 2:** Using OSX, I can successfully plot and display my grayscale histogram using matplotlib.

However, when I go over to my Ubuntu 14.04 machine and execute _the exact same code_ all I see are my images:

[![Image 4: Figure 3: I have executed the *exact same* code on my Ubuntu system in the plotting virtual environment. All I see are my images -- where did my histogram go? Why is there no error message?](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20457'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/07/matplotlib_ubuntu_not_showing.jpg)

**Figure 3:** I have executed the _exact same_ code on my Ubuntu system in the plotting virtual environment. All I see are my images — _where did my histogram go?_ Why is there no error message?

Which leads to the question: _“**Where is the histogram?”**_

As we can see from the terminal output, the script executed just fine. No errors were displayed. No warning messages printed to my console. _**But yet there is not plot!**_

As I hinted at earlier in this post, the missing figure issue is related to the [matplotlib backend](http://matplotlib.org/faq/usage_faq.html#what-is-a-backend) that does all the heavy lifting behind the scenes to prepare the figure.

Popping into a shell, I can access the matplotlib backend using the `matplotlib.get_backend()` :

$ python
Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
\[GCC 4.8.2\] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> matplotlib.get\_backend()
'agg'

On my Ubuntu machine this gives me a value of `agg` ; however, through my testing and debugging, this value needs to be `TkAgg` for the TkInter windowing system (at least when using Ubuntu and Raspbian).

Luckily, we can resolve this issue by using `apt-get` to install a few libraries:

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

But we’re not quite done yet. In order to get matplotlib to recognize the TkInter GUI library, we need to:

*   **Step 1:** Access our `plotting` virtual environment via `workon plotting` .
*   **Step 2:** Use pip to _**uninstall**_ `matplotlib` (since we installed it via pip earlier in this article).
*   **Step 3:** Pull down [matplotlib from the GitHub repo](https://github.com/matplotlib/matplotlib.git).
*   **Step 4:** Install `matplotlib` from source using `setup.py` .

I can accomplish these steps using the following commands:

$ workon plotting
$ pip uninstall matplotlib
$ git clone https://github.com/matplotlib/matplotlib.git
$ cd matplotlib
$ python setup.py install

Again, you’ll want to ensure that you have installed TkInter via `apt-get` before performing these steps.

After `matplotlib` has been installed via source, let’s execute the `get_backend()` function again:

$ python
Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
\[GCC 4.8.2\] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> matplotlib.get\_backend()
'TkAgg'

Sure enough, we now see the `TkAgg` is being used as the `matplotlib` backend.

**_Note:_** _You can explicitly instruct `matplotlib` to use the `TkAgg` backend by making a call to `matplotlib.use("TkAgg")` ; however, this won’t do you much good if the TkInter dependencies are not installed._

And now when we execute our `grayscale_histogram.py` script, just like above:

$ python grayscale\_histogram.py

_**We should now see both our grayscale image along with our histogram:**_

[![Image 5: Figure 4: Success! Our matplotlib figure is now showing up! All we need to do was change the matplotlib backend.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20457'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/07/matplotlib_ubuntu_showing.jpg)

**Figure 4:** Success! Our matplotlib figure is now showing up! All we need to do was change the matplotlib backend.

We have now fixed our issue — matplotlib figures are successfully being displayed on our screen!

Granted, this solution is a bit of a pain in the ass, but it’s fairly straightforward and gets the job done. If you have any other suggestions or comments, please feel free to leave them in the comments section.

What about the Raspberry Pi?
----------------------------

The Raspbian operating system, which many Raspberry Pi’s run, is Debian based just like Ubuntu. If you are having the same problems with matplotlib figures not displaying on your Raspberry Pi, the fix detailed in this blog post will resolve your plotting woes.

Can’t you just install matplotlib via apt-get?
----------------------------------------------

The astute Debian user may be wondering why I didn’t simply install `matplotlib` via `apt-get` , like this:

$ sudo apt-get install python-matplotlib

The reason is because I’m a _**heavy user of Python virtual environments**_ and strictly believe in keeping my Python environments sequestered and independent of each other. If you use `apt-get`  to install `matplotlib`  you lose control over what version of `matplotlib`  you want to install — you simply have to use with whatever version is in the `apt-get`  repository. This also muddles your system install of Python which I try to keep as clean as possible.

All that said, every time I have installed `matplotlib`  via `apt-get`  all of my dependencies were correctly installed and I was able to display my figures without a problem, so if you do not care about Python virtual environments, then the `apt-get`  solution is a good way to go. But again, I really recommend using virtual environments.

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled

**I strongly believe that if you had the right teacher you could _master_ computer vision and deep learning.**

Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s _not_ the case.

All you need to master computer vision and deep learning is for someone to explain things to you in _simple, intuitive_ terms. _And that’s exactly what I do_. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to _successfully_ and _confidently_ apply computer vision to your work, research, and projects. Join me in computer vision mastery.

**Inside PyImageSearch University you'll find:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ hours** of on-demand video
*   ✓ **Brand new courses released _regularly_**, ensuring you can keep up with state-of-the-art techniques
*   ✓ **Pre-configured Jupyter Notebooks in Google Colab**
*   ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
*   ✓ Access to **centralized code repos for _all_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

Summary
-------

In this blog post I detailed how to resolve a pesky issue where `matplotlib`  figures are not displayed to your screen. Symptoms of this problem include clean script execution (i.e. no error messages and no warnings) printed to your terminal, and yet your plot is not displayed. I have regularly encountered this problem when using Debian based operating systems such as Ubuntu and Raspbian. The problem is only further compounded when using Python virtual environments.

Resolving this `matplotlib`  issue involves manually installing dependencies via `apt-get`  and adjusting the [matplotlib backend](http://matplotlib.org/faq/usage_faq.html#what-is-a-backend) to use `TkAgg` , followed by compiling and installing `matplotlib`  from source. Afterwards, the issue seems to be resolved.

While this post wasn’t related to computer vision, the `matplotlib`  library is heavily used in the scientific Python community, so not having your `matplotlib`  figures displayed can be extremely frustrating and annoying. I hope this post helps other readers who encounter a similar problem.

I’ll be back next week with more computer vision posts!

![Image 6](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### Join the PyImageSearch Newsletter and Grab My FREE 17-page Resource Guide PDF

Enter your email address below to **join the PyImageSearch Newsletter** and **download my FREE 17-page Resource Guide PDF** on Computer Vision, OpenCV, and Deep Learning.