2017-06-19 85 views
0

在IPython中使用该最小的示例(Python 2.7):matplotlib不能解码UTF-8胶乳

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') 

我正在与结束的长错误消息:

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

如果我打印unic,unicen或str(unicen),一切都很好,这意味着matplotlib似乎无法处理编码。 str(unic)会导致相同的错误,但unic.encode('utf-8')确实在打印信息中处理了它。

我已经开始使用添加# - - 编码:utf-8 - - 和unichr(0xB0),然后尝试了我找到的所有其他解决方案。实际上,uni.encode()是另一个失败的解决方案。我究竟做错了什么?

----------------------------------编辑---------- --------------------

下面的答案解决了我上面的问题,但是当我尝试使用乳胶时发生同样的错误,所以它看起来像乳胶和matplotlib不能正常工作。

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') 

回答

0

定义你传递给xlabel为Unicode太字符串:

# -- 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') 

输出

下面这个简单的脚本导致此错误(已经与下面的建议修正):

enter image description here

+0

'你'...'',没必要,因为'\ D'不是有效的转义,但更明确。 'from __future__ import unicode_literals'也是一个选项。 – dhke

+0

@dhke你是对的。在这种情况下,'plt.xlabel('$ \ Delta $ [%s]'%(unicen),size ='xx-large')'是正确的。如果使用'str.format','u'...''是必须的:'plt.xlabel(u'$ \ Delta $ [{}]'。format(unicen),size ='xx-large') ' – FJSevilla