简体   繁体   English

不能“将matplotlib.pyplot导入为plt”

[英]Can't “import matplotlib.pyplot as plt”

Can't get matplotlib.pyplot to import. 无法获取要导入的matplotlib.pyplot。 Have upgraded my pi to Jessie, Python3.4, installed matplotlib from source. 已将我的pi升级到Jessie,Python3.4,从源代码安装了matplotlib。 Here's some code I got from this site and modified to try and debug: 这是我从这个站点获得的一些代码,并经过修改以尝试和调试:

#!/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 :(")

results in: 结果是:

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

So the backend is GTK3AGG? 那么后端是GTK3AGG? Why doesn't the capitalization match the supported backends list? 为什么大小写不匹配支持的后端列表? If I remove # from #import matplotlib.pyplot as p the import will fail and I get: 如果我从#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 is listed as a supported backend but fails here. cairo被列为受支持的后端,但在此处失败。 I'm not sure what to try next. 我不确定下一步该尝试什么。 I have been trying to get a matplotlib example to work off and on for about 2 years from the book 'Raspberry Pi Cookbook for Python Programmers'. 我一直试图从“Raspberry Pi Cookbook for Python Programmers”一书中获得一个matplotlib示例,以便继续工作大约2年。 I'm almost ready to give up again. 我几乎准备好再次放弃。

The answer was in macplotlib.use() . 答案是在macplotlib.use()中 As it notes, you must use use() before the matplotlib.pyplot import. 如上所述,您必须在matplotlib.pyplot导入之前使用use()。 I had to try several of the backbends found above to find one that works. 我不得不尝试上面找到的几个后弯来找到一个有效的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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