在Windows上使用对数刻度的matplotlib时出现Unicode错误
我正在使用Python 2.6和matplotlib。如果我运行matplotlib画廊页面提供的示例代码histogram_demo.py,它运行得很好。我把这个脚本简化了很多:
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
ax.set_yscale('log') # <---- add this line to generate the error
plt.show()
但是在执行到plt.show()
这一行时,我遇到了这个错误:
TypeError: coercing to Unicode: need string or buffer, dict found
我尝试把后端(backend)改成很多不同的值,但都没有用。我现在使用的是Qt4Agg
。这是不是字体的问题?看起来应该是我配置上的问题。注意:因为其他问题,我刚刚重新安装了Python 2.6、matplotlib、numpy和scipy。我还有一台运行Python 2.6的XP电脑,它可以顺利执行这两个版本的脚本,没有任何错误。希望有人能帮我。非常感谢!
5 个回答
我今天也遇到了同样的问题,后来在GitHub上找到了原因。
https://github.com/matplotlib/matplotlib/issues/198
解决这个问题的办法是删除 .matplotlib/fontList.cache
这个文件,这个方法对我有效。
我之前也遇到过同样的问题,使用的是matplotlib 0.98.5.2版本。我通过升级到matplotlib 1.0.1解决了这个问题(0.99.3版本没用),或者我也可以删除我的~/.matplotlib文件夹。不太清楚在Windows上该怎么做。
这是matplotlib字体管理中的一个错误。在我的电脑上,这个错误出现在文件/usr/lib/pymodules/python2.6/matplotlib/font_manager.py的第1220行。我在下面的代码片段中标出了变化;这个问题在matplotlib的最新版本中已经修复了。
if best_font is None or best_score >= 10.0:
verbose.report('findfont: Could not match %s. Returning %s' %
(prop, self.defaultFont))
[+]result = self.defaultFont[fontext]
[-]result = self.defaultFont
print "defaultFont", result
else:
verbose.report('findfont: Matching %s to %s (%s) with score of %f' %
(prop, best_font.name, best_font.fname, best_score))
result = best_font.fname
print "best_font", result
这个错误只会在没有找到合适的字体时发生,这时字体管理器会使用默认字体。因此,这个错误看起来没有明显的原因,可能是因为安装的字体发生了变化。
希望这能帮到你!