2017-06-19 62 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