3

Can't get matplotlib.pyplot to import. Have upgraded my pi to Jessie, Python3.4, installed matplotlib from source. 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? 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:

** (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. 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'. I'm almost ready to give up again.

1
  • Try installing cairocffi or pycairo? Commented May 31, 2017 at 8:24

1 Answer 1

2

The answer was in macplotlib.use(). As it notes, you must use use() before the matplotlib.pyplot import. 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.