尝试导入 Matplotlib.pyplot 时出现“UnicodeDecodeError”

尝试导入 Matplotlib.pyplot 时出现“UnicodeDecodeError”

当尝试运行以

import numpy as np
import matplotlib.pyplot as plt

我收到以下错误信息:

/usr/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
Traceback (most recent call last):
  File "/home/kurt/Documents/Python/tax_rates.py", line 2, in <module>
    import matplotlib.pyplot as plt
  File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 29, in <module>
    import matplotlib.colorbar
  File "/usr/lib/python2.7/dist-packages/matplotlib/colorbar.py", line 34, in <module>
    import matplotlib.collections as collections
  File "/usr/lib/python2.7/dist-packages/matplotlib/collections.py", line 27, in <module>
    import matplotlib.backend_bases as backend_bases
  File "/usr/lib/python2.7/dist-packages/matplotlib/backend_bases.py", line 62, in <module>
    import matplotlib.textpath as textpath
  File "/usr/lib/python2.7/dist-packages/matplotlib/textpath.py", line 15, in <module>
    import matplotlib.font_manager as font_manager
  File "/usr/lib/python2.7/dist-packages/matplotlib/font_manager.py", line 1421, in <module>
    _rebuild()
  File "/usr/lib/python2.7/dist-packages/matplotlib/font_manager.py", line 1406, in _rebuild
    fontManager = FontManager()
  File "/usr/lib/python2.7/dist-packages/matplotlib/font_manager.py", line 1044, in __init__
    self.ttffiles = findSystemFonts(paths) + findSystemFonts()
  File "/usr/lib/python2.7/dist-packages/matplotlib/font_manager.py", line 324, in findSystemFonts
    for f in get_fontconfig_fonts(fontext):
  File "/usr/lib/python2.7/dist-packages/matplotlib/font_manager.py", line 276, in get_fontconfig_fonts
    stderr=subprocess.PIPE)
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1340, in _execute_child
    raise child_exception
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

我尝试使用以下命令重新安装 Python 和 Matplotlib

sudo apt-get --reinstall install python
sudo apt-get --reinstall install python-matplotlib

但无济于事。如何才能让 Pyplot 正确导入?

答案1

感谢您的评论。我尝试了 Jos 的建议,在 的开头添加了以下几行tax_rates.py

import sys
reload(sys)
sys.setdefaultencoding('utf8')

我很高兴地看到脚本现在可以运行并生成一个图表(见下面的 Atom 编辑器的屏幕截图)。

在此处输入图片描述

不过,我欢迎一个更“永久”的解决方案。

tax_rates.pyPS 为供您参考,下面复制了整个脚本。

import sys
reload(sys)
sys.setdefaultencoding('utf8')

import numpy as np
import matplotlib.pyplot as plt

# income = np.linspace(0,2e6,2001)

thresholds = np.array([0, 9725, 37650, 190150, 413350, 415050])

print(thresholds)

plt.figure()
plt.plot(thresholds,thresholds)
plt.show()

相关内容