Python: Imported matplotlib but unable to use imshow

Python: Imported matplotlib but unable to use imshow … here is a solution to the problem.

Python: Imported matplotlib but unable to use imshow

I

work on a Windows machine (as a host) as a virtual-box guest in Ubuntu, and I’m trying to run my python script from the terminal. I’m having trouble installing matplotlib using pip install. I managed to install it using

it

sudo apt-get install python-matplotlib

However, I can’t bring up the image I created in the code:

import numpy as np 
import matplotlib.pyplot as plt
import random as random
from random import randrange

image = plt.imshow(mymatrix)
plt.show() 

If I import matplotlib as:

import matplotlib as plt

I

get the following error when I try to run the script:

AttributeError: ‘module’ object has no attribute ‘imshow’

If I import matplotlib as:

import matplotlib.pyplot as plt

I get the following error:

raise ImportError, str(msg) + ‘, please install the python-tk package’
ImportError: No module named _tkinter, please install the python-tk
package

When trying to install python-tk with “pip install python-tk”, this is the result I get:

~/ising $ pip install python-tk Collecting python-tk Could not find
a version that satisfies the requirement python-tk (from versions: )
No matching distribution found for python-tk

I’m not sure if I installed matplotlib incorrectly from the start. I know pyplot doesn’t automatically import with matplotlib, is the same true for installing it from the console? It seems like I’ve tried everything at this stage.

Solution

The problem seems to be that you don’t have a graphic backend installation. The error you are encountering with Python Tk is happening because usually Tk comes with any Python distribution, so you should at least have it. You can install any Python bindings (binds) for Tk, Pyqt4, Pyqt5, Wx, GTK (and possibly others) to get an interactive graphical backend for work. Check the package repository for the actual package name to install.

Keep in mind that functions like imshow are part of the (sub)package matplotlib.pyplot, not matplotlib itself. If you intend to execute plt.imshow(...), import matplotlib as plt is wrong. The correct import is from matplotlib import pyplot as plt or import matplotlib.pyplot as plt.

Related Problems and Solutions