不能将matplotlib.pyplot导入为plt"

时间:2017-05-30 22:10:52

标签: python python-2.7 matplotlib raspberry-pi python-3.4

无法导入matplotlib.pyplot。已将我的pi升级到Jessie,Python3.4,从源代码安装了matplotlib。 这是我从这个网站获得的一些代码,并经过修改以尝试和调试:

#!/usr/bin/python3.4
#find_backends.py
#from pylab import *
import time

import matplotlib as mpl
import matplotlib.backends
#import matplotlib.pyplot as p
import os.path


def is_backend_module(fname):
    """Identifies if a filename is a matplotlib backend module"""
    return fname.startswith('backend_') and fname.endswith('.py')

def backend_fname_formatter(fname): 
    """Removes the extension of the given filename, then takes away the leading 'backend_'."""
    return os.path.splitext(fname)[0][8:]

print("thebackend= " + mpl.get_backend())
# get the directory where the backends live
backends_dir = os.path.dirname(matplotlib.backends.__file__)
print("backends_dir: \t" + str(backends_dir))

# filter all files in that directory to identify all files which provide a backend
backend_fnames = filter(is_backend_module, os.listdir(backends_dir))

backends = [backend_fname_formatter(fname) for fname in backend_fnames]

print("supported backends: \t" + str(backends))

# validate backends
backends_valid = []
for b in backends:
    try:
        p.switch_backend(b)
        backends_valid += [b]
    except:
        continue

print("valid backends: \t" + str(backends_valid))


# try backends performance
for b in backends_valid:

    ion()
    try:
        p.switch_backend(b)


        clf()
        tstart = time.time()               # for profiling
        x = arange(0,2*pi,0.01)            # x-array
        line, = plot(x,sin(x))
        for i in arange(1,200):
            line.set_ydata(sin(x+i/10.0))  # update the data
            draw()                         # redraw the canvas

        print(b + ' FPS: \t' , 200/(time.time()-tstart))
        ioff()

    except:
        print(b + " error :(")

结果:

thebackend= GTK3Agg
backends_dir:   /usr/local/lib/python3.4/dist-packages/matplotlib/backends
supported backends:     ['agg', 'qt5', 'mixed', 'template', 'cairo', 'gtkcairo', 'gtk3', 'webagg_core', 'gtk3cairo', 'pdf', 'gdk', 'ps', 'wx', 'wxagg', 'qt5agg', 'macosx', 'qt4agg', 'qt4', 'nbagg', 'gtkagg', 'tkagg', 'pgf', 'webagg', 'svg', 'gtk3agg', 'gtk']
valid backends:     []


------------------
(program exited with code: 0)
Press return to continue

那么后端是GTK3AGG?为什么大小写与支持的后端列表不匹配? 如果我从#import matplotlib.pyplot中删除#作为p导入将失败,我得到:

** (find_backends.py:1057): WARNING **: Error retrieving accessibility bus address: org.freedesktop.DBus.Error.ServiceUnknown: The name org.a11y.Bus was not provided by any .service files
Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_cairo.py", line 33, in <module>
    import cairocffi as cairo
ImportError: No module named 'cairocffi'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_cairo.py", line 36, in <module>
    import cairo
ImportError: No module named 'cairo'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "find_backends.py", line 8, in <module>
    import matplotlib.pyplot as p
  File "/usr/local/lib/python3.4/dist-packages/matplotlib/pyplot.py", line 115, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup
    globals(),locals(),[backend_name],0)
  File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_gtk3agg.py", line 12, in <module>
    from .backend_cairo import cairo, HAS_CAIRO_CFFI
  File "/usr/local/lib/python3.4/dist-packages/matplotlib/backends/backend_cairo.py", line 38, in <module>
    raise ImportError("Cairo backend requires that cairocffi or pycairo is installed.")
ImportError: Cairo backend requires that cairocffi or pycairo is installed.


------------------
(program exited with code: 1)
Press return to continue

cairo被列为受支持的后端,但在此处失败。我不确定下一步该尝试什么。我一直试图让一个matplotlib的例子在本书#Raspberry Pi Cookbook for Python Programmers&#39;中工作了大约2年。我几乎准备好再次放弃。

1 个答案:

答案 0 :(得分:3)

答案在macplotlib.use()。如上所述,您必须在matplotlib.pyplot导入之前使用use()。我不得不尝试上面找到的几个后弯,找到一个有效的后弯。

import numpy as np
import matplotlib as mpl
mpl.use('tkagg')    #YAAA!!  this finally makes the Damn thing work
import matplotlib.pyplot as plt