python - Matplotlib 中的 Unicode 字符串注释

标签 python numpy unicode matplotlib

我有以下代码,当标签有 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)

最佳答案

您需要将字符串解码为 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, ...)会起作用的。

关于python - Matplotlib 中的 Unicode 字符串注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28454584/

相关文章:

python - cv2.cornerSubPix() 函数返回 None 值

python - 计算 xarray 中缺失数据的相关性

hadoop - 如何将汉字插入 hive 表?

python - 使用 beautifulsoup 获取 HTML 中链接标签内的标题

python - 将键值放入Python字典列表中

python - Pandas :如何更快地应用于数据框?

python - 沿第一维轴按列缩放 3d numpy 数组

html - 如何更改unicode字体颜色

ruby-on-rails - 字符编码,如何区分?

python - 如何连接 2 个数据框并基于过滤器 pyspark 添加新列