Wednesday, November 17, 2010

simple text in matplotlib



This post is a "note to myself" about fonts and text using matplotlib. It can be hard to remember things like what is a FontProperties object and what kind of object is a font_dict, so here is a little example. It shows how to get (1) the default font with italics, (2) a default font in a particular "family"---sans-serif, (3) and (4) two named fonts and (5) a font loaded from a particular .ttf file. Notice that in (4) we do not observe the desired response to changing the 'weight'---I'm not sure why yet.

The second figure shows a change in the font using rc. It looks nice, takes several seconds to draw, and does not give the desired italics. They're all here as a reference. Perhaps they'll be of some use to you as well.


output:


:family=Arial:style=normal:variant=normal:weight=normal:stretch=normal:file=/Library/Fonts/Arial Italic.ttf:size=12.0



import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

# can take a 'fontdict', Python dictionary
x,y = 0.1,0.1
fd = { 'fontsize':24, 'style':'italic',
'va':'center', 'ha':'left' }
plt.text(x,y,'1. text ' + 'default',**fd)

fd['family'] = 'sans-serif'
y += 0.1
plt.text(x,y,'1. text ' + 'sans-serif',**fd)

L = ['Arial','Helvetica']
for i,n in enumerate(L):
fd['fontname'] = n
y += 0.1
plt.text(x,y,str(i+2) + '. text ' + n,**fd)

fd['weight'] = 1000
y += 0.1
plt.text(x,y,'4. text--not properly bolded',**fd)

fp = fm.FontProperties(family='Arial',
fname='/Library/Fonts/Arial Italic.ttf')
print fp
y += 0.1
plt.text(x,y,'5. text Arial--named',
fontsize=24,
fontproperties=fp)

ax = plt.axes()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
plt.savefig('example.png')



from matplotlib import rc
import matplotlib.pyplot as plt

x,y = 0.1,0.1

rc('font',**{'family':'sans-serif',
'sans-serif':['Helvetica'],
'style':'italic',
'size':24 })
rc('text', usetex=True)
y += 0.1
plt.text(x,y,'text using rc--not properly italic')


ax = plt.axes()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
plt.savefig('example.png')

No comments: