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

问题描述 投票:15回答:4

我正在尝试将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字体吗?如果是这样,我怎么能得到它?我知道自从我在Illustrator和许多其他程序中看到它后,我的系统上都有Helvetica。

我使用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'

任何想法如何解决这个问题?

谢谢。

python macos numpy matplotlib scipy
4个回答
17
投票

解决方案是使用fondu将.dfont Helvetica字体从Mac OS X转换为.ttf,然后将其放在Matplotlib查找的mpl-data / fonts目录中。这解决了这个问题。


15
投票

OS X 10.11 El Capitan和Python 3(基于this post)的逐步解决方案。

  1. 安装fondu: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. 将我们从dfont制作的Helvetica副本转换为ttfcd /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')

5
投票

我在安装Helvetica时仍遇到问题。我在.dfont文件中使用了fondu,现在在mpl-data/fonts/ttf目录中有Helvetica.ttf:

$ pwd
/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf
$ ls
COPYRIGHT.TXT             RELEASENOTES.TXT          STIXSizFiveSymReg.ttf     Vera.ttf                  VeraSeBd.ttf
Helvetica.ttf             STIXGeneral.ttf           STIXSizFourSymBol.ttf     VeraBI.ttf                cmb10.ttf
HelveticaBold.ttf         STIXGeneralBol.ttf        STIXSizFourSymReg.ttf     VeraBd.ttf                cmex10.ttf
HelveticaBoldOblique.ttf  STIXGeneralBolIta.ttf     STIXSizOneSymBol.ttf      VeraIt.ttf                cmmi10.ttf
HelveticaLight.ttf        STIXGeneralItalic.ttf     STIXSizOneSymReg.ttf      VeraMoBI.ttf              cmr10.ttf
HelveticaLightOblique.ttf STIXNonUni.ttf            STIXSizThreeSymBol.ttf    VeraMoBd.ttf              cmss10.ttf
HelveticaOblique.ttf      STIXNonUniBol.ttf         STIXSizThreeSymReg.ttf    VeraMoIt.ttf              cmsy10.ttf
LICENSE_STIX              STIXNonUniBolIta.ttf      STIXSizTwoSymBol.ttf      VeraMono.ttf              cmtt10.ttf
README.TXT                STIXNonUniIta.ttf         STIXSizTwoSymReg.ttf      VeraSe.ttf

我编辑了我的~/.matplotlib/matplotlibrc文件(根据--verbose-debug加载的文件):

font.serif          : Palatino, Bitstream Vera Serif, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman,
     Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
font.sans-serif     : Helvetica #, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Avant Garde, sans-serif

但是在绘图时我得到了这个错误:

/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/site-packages/matplotlib/font_manager.py:1216: 
UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to Bitstream Vera Sans
  (prop.get_family(), self.defaultFamily[fontext]))

如果我将默认字体设置为serif,那么Palatino就可以了。

有小费吗?


0
投票

如果它可以帮助任何人,我写了一个脚本,自动将.ttf字体从自定义文件夹添加到mpl-data。将.ttf文件放在某个文件夹中,然后运行此脚本来移动它们。

#!/usr/bin/env python3
# Imports
import os
import re
import shutil
from glob import glob
from matplotlib import matplotlib_fname
from matplotlib import get_cachedir

# Copy files over
_dir_data = re.sub('/matplotlibrc$', '', matplotlib_fname())
dir_source = '<your-font-directory-here>'
dir_dest = f'{_dir_data}/fonts/ttf'
# print(f'Transfering .ttf and .otf files from {dir_source} to {dir_dest}.')
for file in glob(f'{dir_source}/*.[ot]tf'):
    if not os.path.exists(f'{dir_dest}/{os.path.basename(file)}'):
        print(f'Adding font "{os.path.basename(file)}".')
        shutil.copy(file, dir_dest)

# Delete cache
dir_cache = get_cachedir()
for file in glob(f'{dir_cache}/*.cache') + glob(f'{dir_cache}/font*'):
    if not os.path.isdir(file): # don't dump the tex.cache folder... because dunno why
        os.remove(file)
        print(f'Deleted font cache {file}.')

这最初出现在this stackoverflow post

© www.soinside.com 2019 - 2024. All rights reserved.