无法在 Mac OS X 10.6 上的 Python 中将 Matplotlib 中的字体更改为 Helvetica

2024-03-27

我正在尝试将 matplotlib 字体更改为 helvetica,我想在 PDF 图中使用它。我尝试以下操作:

import matplotlib
matplotlib.use('PDF')
import matplotlib.pylab as plt
from matplotlib import rc
plt.rcParams['ps.useafm'] = True
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
plt.rcParams['pdf.fonttype'] = 42

这不起作用——当我使用 --verbose-debug 运行代码时,出现错误:

backend WXAgg version 2.8.10.1
/Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/matplotlib/__init__.py:833: UserWarning:  This call to matplotlib.use() has no effect
because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
findfont: Could not match :family=sans-serif:style=normal:variant=normal:weight=normal:stretch=normal:size=medium. Returning /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/matplotlib/mpl-data/fonts/ttf/Vera.ttf
Assigning font /F1 = /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/matplotlib/mpl-data/fonts/ttf/Vera.ttf
Embedding font /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/matplotlib/mpl-data/fonts/ttf/Vera.ttf
Writing TrueType font

所以显然它找不到 Helvetica。我不知道为什么。我在 mpl-data 的 afm 目录中有 Helvetica,当 matplotlib 启动时,它会读取它并输出:

createFontDict: /Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/site-packages/matplotlib/mpl-data/fonts/afm/Helvetica.afm

我还需要特殊的 .ttf Helvetica 字体吗?如果是这样,我怎样才能得到它?我知道我的系统上有 Helvetica,因为我在 Illustrator 和许多其他程序中看到它。

我正在使用 Enthought Python 发行版,如下所示:

$ python
Enthought Python Distribution -- http://www.enthought.com
Version: 6.2-2 (32-bit)

Python 2.6.5 |EPD 6.2-2 (32-bit)| (r265:79063, May 28 2010, 15:13:03) 
[GCC 4.0.1 (Apple Inc. build 5488)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> matplotlib.__version__
'0.99.3'

有什么想法可以解决这个问题吗?

thanks.


OS X 10.11 El Capitan 和 Python 3 的分步解决方案(基于这个帖子 http://blog.olgabotvinnik.com/blog/2012/11/15/2012-11-15-how-to-set-helvetica-as-the-default-sans-serif-font-in/).

  1. 安装火锅:brew install fondu
  2. 找出 matplotlib 位置:

    python3 -c "import matplotlib ; print(matplotlib.matplotlib_fname())" 
    

    对我来说是/usr/local/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc

  3. 制作 Helvetica 的副本:

    mkdir ~/Desktop/font_copies
    cp /System/Library/Fonts/Helvetica.dfont ~/Desktop/font_copies
    
  4. 转换我们制作的 Helvetica 副本dfont to ttf:

    cd /usr/local/lib/python3.5/site-packages/matplotlib/mpl-data/fonts/ttf/
    fondu -show ~/Desktop/font_copies/Helvetica.dfont
    
  5. 删除字体缓存:rm ~/.matplotlib/fontList.py3k.cache

完毕!现在您可以使用 Helvetica:

import matplotlib.pyplot as plt
plt.rc('font', family='Helvetica')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法在 Mac OS X 10.6 上的 Python 中将 Matplotlib 中的字体更改为 Helvetica 的相关文章

随机推荐