2010-07-04 6 views
13

Sto cercando di cambiare il tipo di carattere matplotlib a helvetica, che mi piacerebbe utilizzare in una trama PDF. Provo il seguente:non può cambiare tipo di carattere Helvetica in Matplotlib in Python su Mac OS X 10.6

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 

Questo non funziona - quando ho eseguito il mio codice con --verbose-debug, ottengo l'errore:

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 

Quindi a quanto pare non riesce a trovare Helvetica. Non sono sicuro del perché. Ho Helvetica nella directory AFM di MPL-dati, e quando matplotlib avvia lo legge e uscite:

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

Ho bisogno di una speciale .ttf font Helvetica in aggiunta? Se è così, come posso ottenerlo? So di avere Helvetica sul mio sistema da quando lo vedo in Illustrator e in molti altri programmi.

Sto usando la distribuzione Enthought Python come segue:

$ 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' 

Tutte le idee come questo può essere fissato?

grazie.

risposta

15

La soluzione è utilizzare il fondu per convertire il font .dfont Helvetica da Mac OS X in .ttf, quindi posizionarlo nella directory mpl-data/fonts in cui appare Matplotlib. Ciò risolve il problema.

+3

Grazie per avermi fatto la domanda e aver risposto - sono sicuro che questo mi sarà utile qualche volta, e questo è esattamente il genere di cosa per cui è stato creato StackOverflow. – ShreevatsaR

+0

Potresti fornire maggiori dettagli? La soluzione passo passo di Max Malysh funziona come un fascino! – meduz

5

Ho ancora problemi con l'installazione di Helvetica. fondu Ho usato sul file .dfont e ora hanno Helvetica.ttf nella mpl-data/fonts/ttf directory:

$ 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 

E ho modificato il mio file ~/.matplotlib/matplotlibrc (che è quella caricata in base al --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 

ma ottengo questo errore durante la stampa:

/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])) 

Se ho impostato il carattere predefinito come serif, Palatino si presenta bene.

Qualche consiglio?

+3

La soluzione è rimuovere i file fontList.cache in '~/.matplotlib/fontList.cache'. Ci è voluto un po 'di tempo e mi ha spinto a scrivere un [tutorial] completo (http://blog.olgabotvinnik.com/post/35807476900/how-to-set-helvetica-as-the-default-sans-serif- font-in) su come modificare i font di default in matplotlib. –

12

soluzione Step-by-step per OS X 10.11 El Capitan e Python 3 (basata su this post).

  1. Installare fondu: brew install fondu
  2. Ottieni matplotlib posizione:

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

    Per me è /usr/local/lib/python3.5/site-packages/matplotlib/mpl-data/matplotlibrc

  3. Eseguire una copia di Helvetica:

    mkdir ~/Desktop/font_copies 
    cp /System/Library/Fonts/Helvetica.dfont ~/Desktop/font_copies 
    
  4. Convert la copia Helvetica abbiamo fatto dfont-ttf:

    cd /usr/local/lib/python3.5/site-packages/matplotlib/mpl-data/fonts/ttf/ 
    fondu -show ~/Desktop/font_copies/Helvetica.dfont 
    
  5. Rimuovere cache dei font: rm ~/.matplotlib/fontList.py3k.cache

Fatto! Ora è possibile utilizzare Helvetica:

import matplotlib.pyplot as plt 
plt.rc('font', family='Helvetica') 
+0

Questa soluzione passo-passo funziona perfettamente e dovrebbe essere aggiornata! – meduz

+0

Questa dovrebbe essere la risposta accettata. Grazie mille! –

0

In caso aiuta nessuno, ho scritto uno script di shell che aggiunge automaticamente .ttf font da una cartella personalizzata per mpl-data. È sufficiente posizionare i file .ttf in una cartella fonts che si trova nella stessa directory di questo script. Personalmente, ho inserito questo file e la cartella fonts in una cartella dotfiles che sincronizzo su tutte le distribuzioni con git.

In ogni caso, qui è:

#!/bin/bash 
# This function sets up any .ttf fonts contained in the <fonts> directory to be detected by matplotlib 
# Normally matplotlib just includes a couple open-source .ttf files, but this way we can carry many more 
# options across different systems. 
# See: https://olgabotvinnik.com/blog/2012-11-15-how-to-set-helvetica-as-the-default-sans-serif-font-in/ 

# We want empty loops if nothing available, so turn on null-globbing 
shopt -s nullglob 

# Add the fonts 
mpldir="$(python -c "import matplotlib; print(matplotlib.matplotlib_fname())")" # this is the location of matplotlib's default "matplotlibrc" file 
mfontdir="${mpldir%matplotlibrc}/fonts/ttf" # the same directory should contain a "fonts" folder 
echo "Transfering .ttf files in \"fonts\" folder to \"$mfontdir\"..." 
for font in fonts/*.ttf; do 
    if [ ! -r "$mfontdir/${font##*/}" ]; then # only copy if not already present 
    echo "Adding font \"${font##*/}\"..." 
    cp "$font" "$mfontdir/" 
    fi 
done 

# Then delete the font cache(s) so fonts are loaded on next startup 
# For get_cachedir see: https://stackoverflow.com/a/24196416/4970632 
cachedir=$(python -c "import matplotlib; print(matplotlib.get_cachedir())") 
caches=($cachedir/*.cache) # array listing of all font caches 
for cache in "${caches[@]}"; do 
    if [ ! -d "$cache" ]; then # ignore the tex.cache folder 
    echo "Deleting cache \"$cache\"..." 
    rm "$cache" 
    fi 
done 

Questo è originariamente apparso in this stackoverflow post.