Alex
Alex

Reputation: 11

matplotlib can't decode utf-8 when used with latex

Using this minimal example in ipython (python 2.7):

from matplotlib import pylab
unic = u'\xb0'
unicen = unic.encode('utf-8')
plt.plot([1,2],[3,4])
plt.xlabel(r'$\Delta$ [%s]'%(unicen), size='xx-large')

I am getting a long error message which ends with:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 10: ordinal not in range(128)

If I print unic, unicen, or str(unicen), everything is fine, which means that matplotlib seems not to be able to handle the encoding. str(unic) leads to the same error, but unic.encode('utf-8') did take care of it in the print message.

I have started using adding # -- coding: utf-8 -- and unichr(0xB0), then tried all other solutions which I found. Actually, uni.encode() is another solution which failed. What am I doing wrong?

----------------------------------EDIT------------------------------

The answer below is solving my problem above, but the SAME ERROR occurs when I try to use latex, so it seems like latex and matplotlib don't work together properly.

Here the simple script which causes this error (already corrected with the suggestion below):

from matplotlib import pylab
unic = u'\xb0'

plt.plot([1,2],[3,4])

plt.rc ('text', usetex=True)
plt.rc ('font', family='serif')
plt.rc ('font', serif='Computer Modern Roman')

plt.xlabel(u'$\Delta$ [%s]'%(unic), size='xx-large')

Upvotes: 1

Views: 1114

Answers (1)

FJSevilla
FJSevilla

Reputation: 4513

Define the string that you pass to xlabel as unicode too:

 # -- coding: utf-8 --

from matplotlib import pylab
unicen = u'\xb0'
plt.plot([1,2],[3,4])
plt.xlabel(u'$\Delta$ [%s]'%(unicen), size='xx-large')

Output:

enter image description here

Upvotes: 1

Related Questions