【问题标题】:Unicode string in Matplotlib annotateMatplotlib 中的 Unicode 字符串注释
【发布时间】:2015-04-11 20:06:26
【问题描述】:

我有以下代码,当标签有一个 unicode 字符串时,注释失败抛出错误,我该如何解决这个问题?

from matplotlib import pyplot as plt
import numpy as Math


X = Math.genfromtxt(inputFile,autostrip=True,comments=None,dtype=Math.float64,usecols=(range(1,dim+1)))
labels = Math.genfromtxt(inputFile,autostrip=True,comments=None,dtype='str',usecols=(0))
Y = some_function(X, 2, 50, 20.0);    
fig = plt.figure()
ax = fig.add_subplot(111)
plt.scatter(Y[:,0],Y[:,1])
for l,x,y in zip(labels,Y[:,0],Y[:,1]):
   ax.annotate('(%s)' %l, xy=(x,y), textcoords='offset points')

plt.grid()
plt.show()

Error :
Traceback (most recent call last):
ax.annotate('(%s)' %unicode(l), xy=(x,y), textcoords='offset points')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 4: ordinal not in range(128)

【问题讨论】:

    标签: python numpy unicode matplotlib


    【解决方案1】:

    您需要将字符串解码为 un​​icode 而不是标准 ASCII (see here):

    from matplotlib import pyplot as plt
    
    l = '\xe2'
    
    plt.annotate('%s' % l, (0, 0))
    # raises UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
    
    plt.annotate('%s' % l.decode('unicode-escape'), (0, 0))
    # works
    

    您还可以像这样将输入文件解码为 un​​icode:

    # converter function that decodes a string as unicode
    conv = {0:(lambda s: s.decode('unicode-escape'))}
    
    labels = np.genfromtxt(inputFile, dtype='unicode', converters=conv, usecols=0)
    

    labels.dtype 然后将是 unicode ('<Ux') 而不是字符串 ('|Sx'),因此 ax.annotate('(%s)' %l, ...) 将起作用。

    【讨论】:

    • 谢谢!第一个选项对我有用,但第二个不起作用
    • 当你说它“不起作用”时,你能更具体一点吗?错误发生在genfromtxt 还是annotate?如果您能在您的问题中显示您的inputFile 的样子,将会很有帮助。
    • 我发现了问题 - 有必要将转换器参数传递给 genfromtxt,它将输入字符串解码为 un​​icode。我已更新我的答案以包含此内容。
    猜你喜欢
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 2021-12-12
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多