fonfonx
fonfonx

Reputation: 1465

Python Unicode Decode Error when importing matplotlib

I try to use matplotlib in my python script but I got this error in the terminal:

Traceback (most recent call last):
  File "graphique.py", line 5, in <module>
    import matplotlib.pyplot as plt
  File "/home/xavier/anaconda/lib/python2.7/site-packages/matplotlib/__init__.py", line 1048, in <module>
    rcParams = rc_params()
  File "/home/xavier/anaconda/lib/python2.7/site-packages/matplotlib/__init__.py", line 897, in rc_params
    fname = matplotlib_fname()
  File "/home/xavier/anaconda/lib/python2.7/site-packages/matplotlib/__init__.py", line 748, in matplotlib_fname
    fname = os.path.join(os.getcwd(), 'matplotlibrc')
  File "/home/xavier/anaconda/lib/python2.7/posixpath.py", line 80, in join
    path += '/' + b
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 66: ordinal not in range(128)

Here is my python code, I simply wrote

# -*- coding: utf-8 -*-
import numpy as np
from math import *
import matplotlib.pyplot as plt

What do I have to do?

Upvotes: 3

Views: 6397

Answers (1)

abarnert
abarnert

Reputation: 366133

The problem is that you have a non-ASCII character in your current working directory.

That actually shouldn't be a problem at all, but it is because of a combination of other things:

  • matplotlib wants to look in your current working directory for a local matplotlibrc file that overrides your default one.
  • Python thinks you're using the C locale instead of the nice UTF-8 locale that Ubuntu 14 should be defaulting to.

So, for a quick workaround, just run your script from a different directory, that has no non-ASCII characters in it.

If you actually want to solve the problem:

  • Make sure you have the latest Ubuntu 14, Anaconda, and matplotlib.
  • From the shell, echo $LANG. The result should be either empty, or something with UTF-8 in it. If not, search AskUbuntu for how to fix that.
  • Make sure your shell and terminal are both set to UTF-8.

From a quick search of the matplotlib issues, this looks like #3516, which looks like it was fixed in #3594, which I think should be in matplotlib 1.4.1+. Also see #3487. So, assuming you $LANG and terminal are correct, and your matplotlib is 1.4.0 or earlier, this is the most likely cause, and updating it (via conda or pip or apt-get or updating Anaconda itself, however you originally installed it) should be the fix.

Or, of course, you can upgrade to Python 3, which will probably either solve the problem, or give you a better error message that tells you exactly what's wrong. (Although, from scanning the issue report, it looks like matplotlib 1.4.0 doesn't have this exact bug in Python 3, only Python 2, as expected… but it may have a related bug…)

Upvotes: 3

Related Questions