在 Windows 上使用带有对数刻度的 matplotlib 时出现 Unicode 错误

发布于 2024-09-14 18:21:18 字数 761 浏览 2 评论 0 原文

我正在使用 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

我尝试将后端更改为许多不同的值 - 没有任何帮助。我正在使用 Qt4Agg。这是字体问题吗?看来应该是和我的配置有关系。注意:由于其他问题,我刚刚安装了 python26、matplotlib、numpy、scipy 的全新副本。我有另一个运行 python26 的 XP 盒子,它执行两个版本的脚本,没有错误。我希望有人能提供帮助。非常感谢。

I'm using python 2.6 and matplotlib. If I run the sample histogram_demo.py provided in the matplotlib gallery page, it works fine. I've simplified this script greatly:

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

I get this error (at the plt.show() line):

TypeError: coercing to Unicode: need string or buffer, dict found

I've tried changing the backend to many different values - nothing helps. I am using Qt4Agg. Is this a font issue? It seems that it must be something with my configuration. Note: Because of other problems, I just installed a fresh copy of python26, matplotlib, numpy, scipy. I have another XP-box running python26 and it executes both versions of the script with no errors. I hope someone can help. Many thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

雨后咖啡店 2024-09-21 18:21:18

这是 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

仅当未找到“好”字体并且字体管理器回退到默认字体时,才会出现此错误。因此,错误的发生没有明显的原因,可能是因为安装的字体发生了变化。

希望有帮助!

This is a bug in the font management of matplotlib, on my machine this is the file /usr/lib/pymodules/python2.6/matplotlib/font_manager.py:1220. I've highlighted the change in the code snippet below; this is fixed in the newest version of 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

This error occurs only if no "good" font was found and the font manager falls back to a default font. Therefore the error occured without apparent reason, probably because of changes in the installed fonts.

Hope that helps!

栀子花开つ 2024-09-21 18:21:18

我在 matplotlib 0.98.5.2 上遇到了同样的问题。我可以通过升级到 matplotlib 1.0.1 (0.99.3 不起作用)或通过清除我的 ~/.matplotlib 目录来修复它。不确定 Windows 的等效项是什么。

I had the same problem with matplotlib 0.98.5.2. I was able to fix it by upgrading to matplotlib 1.0.1 (0.99.3 didn't work), or by blowing away my ~/.matplotlib directory. Not sure what the equivalent is for Windows.

风追烟花雨 2024-09-21 18:21:18

我今天也遇到了同样的问题,我在github中发现了这个问题

https://github.com/matplotlib /matplotlib/issues/198

建议的解决方法是删除 .matplotlib/fontList.cache 文件,这对我有用。

I had the same problem today, and I found the issue in github

https://github.com/matplotlib/matplotlib/issues/198

The proposed workaround is to delete the .matplotlib/fontList.cache file, and worked for me.

臻嫒无言 2024-09-21 18:21:18

我今天遇到了类似的错误,涉及我知道一周前有效的代码。我最近还卸载/重新安装了 Matplotlib 和 Numpy,同时检查其他内容(我正在使用 Python 2.5)。

代码是这样的:

self.ax.cla()
if self.logy: self.ax.set_yscale('log')
self.canvas.draw()

每当它以 self.logy 为 True 运行时,都会失败,如上所述。否则,它工作得很好。

我最终通过卸载 Matplotlib 和 Numpy 并安装它们的最新版本来回避这个问题。然而,引发错误的版本以前使用过,没有任何问题。只有在将旧版本替换为新版本并再次返回后,这种情况才开始发生。

也许卸载/重新安装过程会弄乱配置文件的某些方面。

为了完整起见,以下是给出的完整回溯:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\path\to\file\being\called\by\Tkinter.py", line 1081, in refresh
    self.canvas.draw()
  File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_tkagg.py", line 215, in draw
    FigureCanvasAgg.draw(self)
  File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_agg.py", line 314, in draw
    self.figure.draw(self.renderer)
  File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
    draw(artist, renderer, *kl)
  File "C:\Python25\Lib\site-packages\matplotlib\figure.py", line 773, in draw
    for a in self.axes: a.draw(renderer)
  File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
    draw(artist, renderer, *kl)
  File "C:\Python25\Lib\site-packages\matplotlib\axes.py", line 1735, in draw
    a.draw(renderer)
  File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
    draw(artist, renderer, *kl)
  File "C:\Python25\Lib\site-packages\matplotlib\axis.py", line 742, in draw
    tick.draw(renderer)
  File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
    draw(artist, renderer, *kl)
  File "C:\Python25\Lib\site-packages\matplotlib\axis.py", line 196, in draw
    self.label1.draw(renderer)
  File "C:\Python25\Lib\site-packages\matplotlib\text.py", line 515, in draw
    bbox, info = self._get_layout(renderer)
  File "C:\Python25\Lib\site-packages\matplotlib\text.py", line 279, in _get_layout
    clean_line, self._fontproperties, ismath=ismath)
  File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_agg.py", line 156, in get_text_width_height_descent
    self.mathtext_parser.parse(s, self.dpi, prop)
  File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 2797, in parse
    font_output = fontset_class(prop, backend)
  File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 658, in __init__
    self._stix_fallback = StixFonts(*args, **kwargs)
  File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 900, in __init__
    fullpath = findfont(name)
  File "C:\Python25\Lib\site-packages\matplotlib\font_manager.py", line 1306, in findfont
    if not os.path.exists(font):
  File "C:\Python25\lib\ntpath.py", line 255, in exists
    st = os.stat(path)
TypeError: coercing to Unicode: need string or buffer, dict found

I experienced a similar error today, concerning code that I know for a fact was working a week ago. I also have recently uninstalled/reinstalled both Matplotlib and Numpy, while checking something else (I'm using Python 2.5).

The code went something like this:

self.ax.cla()
if self.logy: self.ax.set_yscale('log')
self.canvas.draw()

Whenever it was run with self.logy as True, it failed as above. Otherwise, it worked perfectly fine.

I ended up sidsteping the issue by uninstalling Matplotlib and Numpy and installing the latest versions of them. However, the version throwing the error had previously been used with no problems. Only after swapping the old version for the newer one and back again did this start happening.

Perhaps the uninstall/reinstall process messes up certain aspects of the configuration files.

For completeness, here is the complete traceback given:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\path\to\file\being\called\by\Tkinter.py", line 1081, in refresh
    self.canvas.draw()
  File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_tkagg.py", line 215, in draw
    FigureCanvasAgg.draw(self)
  File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_agg.py", line 314, in draw
    self.figure.draw(self.renderer)
  File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
    draw(artist, renderer, *kl)
  File "C:\Python25\Lib\site-packages\matplotlib\figure.py", line 773, in draw
    for a in self.axes: a.draw(renderer)
  File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
    draw(artist, renderer, *kl)
  File "C:\Python25\Lib\site-packages\matplotlib\axes.py", line 1735, in draw
    a.draw(renderer)
  File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
    draw(artist, renderer, *kl)
  File "C:\Python25\Lib\site-packages\matplotlib\axis.py", line 742, in draw
    tick.draw(renderer)
  File "C:\Python25\Lib\site-packages\matplotlib\artist.py", line 46, in draw_wrapper
    draw(artist, renderer, *kl)
  File "C:\Python25\Lib\site-packages\matplotlib\axis.py", line 196, in draw
    self.label1.draw(renderer)
  File "C:\Python25\Lib\site-packages\matplotlib\text.py", line 515, in draw
    bbox, info = self._get_layout(renderer)
  File "C:\Python25\Lib\site-packages\matplotlib\text.py", line 279, in _get_layout
    clean_line, self._fontproperties, ismath=ismath)
  File "C:\Python25\Lib\site-packages\matplotlib\backends\backend_agg.py", line 156, in get_text_width_height_descent
    self.mathtext_parser.parse(s, self.dpi, prop)
  File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 2797, in parse
    font_output = fontset_class(prop, backend)
  File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 658, in __init__
    self._stix_fallback = StixFonts(*args, **kwargs)
  File "C:\Python25\Lib\site-packages\matplotlib\mathtext.py", line 900, in __init__
    fullpath = findfont(name)
  File "C:\Python25\Lib\site-packages\matplotlib\font_manager.py", line 1306, in findfont
    if not os.path.exists(font):
  File "C:\Python25\lib\ntpath.py", line 255, in exists
    st = os.stat(path)
TypeError: coercing to Unicode: need string or buffer, dict found
神也荒唐 2024-09-21 18:21:18

感谢您解释问题!

由于我使用的是 Mac OS 10.6 系统安装的 matplotlib(并且由于其他软件包要求,我被困在 Python2.5 上),我对升级 matplotlib 不感兴趣(我只是无法处理 open-源包!)

所以我随机尝试的修复方法是编辑我的 ~/.matplotlib/matplotlibrc
并通过设置 text.usetex : True 启用 LaTex
(因为它显示了一长串支持的字体,所以我认为它可能会更努力地找到“好的”字体)。

不是真正的“修复”,但让我的脚本以最少的修补/停机时间运行。

Thanks for explaining the issue!

Since I'm using the Mac OS 10.6 system install of matplotlib, (and I'm stuck on Python2.5 due to other package requirements) I am not interested in upgrading matplotlib (I just can't handle all the versioning of open-source packages!)

So the fix I randomly tried, which worked, was to edit my ~/.matplotlib/matplotlibrc
and enable LaTex, by setting text.usetex : True
(since it showed a long list of supported fonts, so I thought it might try harder to find a "good" font).

Not a real "fix", but got my script working with minimal tinkering/downtime.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文