简体   繁体   中英

Python: Imported matplotlib but cannot use imshow

I'm working in Ubuntu as Virtual-Box guest on top of Windows machine (as host), and I am attempting to run my python script from the terminal. I had difficulty installing matplotlib using pip install. I managed to install it using

sudo apt-get install python-matplotlib

However, I am unable to bring up an image I have created in my 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 am recieving the following error on attempting to run the script:

AttributeError: 'module' object has no attribute 'imshow'

If I import matplotlib as:

import matplotlib.pyplot as plt

I recieve the following error:

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

On attempting to install python-tk using 'pip install python-tk' this is what I'm getting:

~/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 unsure if I have in fact incorrectly installed matplotlib from the beginning. I am aware pyplot is not automatically imported with matplotlib, could the same be true for installing it from the console? Seems like I have tried everything at this stage.

The problem appears to be that you do not have a graphical backend installed. The error you are getting about Python Tk is happening because normally Tk comes with any Python distribution, so you should have at least that. You can install any Python bindings for Tk, Pyqt4, Pyqt5, Wx, GTK, (possibly others) to get a working interactive graphical backend. Check the package repository for the actual package names to install.

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

According to the documentation here try this

 python -mpip install -U pip
 python -mpip install -U matplotlib

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM