Typography [tʌɪˈpɒɡrəfi]
n.: the style and appearance of printed matter.
Perhaps a “glossed” feature of making graphs, having the right font goes a long way. Not only do we have the advantage of using a “pretty” font that we like, it also provides an aesthetic satisfaction of having everything (e.g. in a PhD thesis) in the same font, i.e. both the text and graph use the same font.
Fonts can be divided into two types: serif and sans-serif. Basically, serif fonts are those where the letters have little “bits” at the end; think of Times New Roman or Garamond as the classic examples. Sans-serif fonts are those that lack these bits, and give it a more “blocky”, clean finish – think of Arial or Helvetica as a classic example.
Typically, serif fonts are better for books/printed materials, whereas sans-serif fonts are better for web/digital content. As it follows, then what about graphs? Especially those that may go out in the public domain (whether it’s through publishing, or in a web site)?
This largely bottles down to user preference, and choosing the right font is not trivial. Supposing that you have (say, from Google Fonts), then there are a few things we need to do (e.g. make sure that your TeX distribution and Illustrator have the font). However, this post is concerned with how we can use custom fonts in a graph generated by Matplotlib, and why this is useful. My favourite picks for fonts include Roboto and Palatino.
To start, let’s generate a histogram of 1000 random numbers from a normal distribution.
The default font in matplotlib, bitstream sans, isn’t the prettiest thing on earth. Does the job but it isn’t my go-to choice if I can change it. Plus, with lots of journals asking for Type 1/TrueType fonts for images, there’s even more reason to change this anyway (matplotlib, by default, generates graphs using Type 3 fonts!). If we now change to Roboto or Palatino, we get the following:
Basically, the bits we need to include at the beginning of our code are here:
# Need to import matplotlib options setting method # Set PDF font types - not necessary but useful for publications from matplotlib import rcParams rcParams['pdf.fonttype'] = 42 # For sans-serif from matplotlib import rc rc("font", **{"sans-serif": ["Roboto"]} # For serif - matplotlib uses sans-serif family fonts by default # To render serif fonts, you also need to tell matplotlib to use LaTeX in the backend. rc("font", **{"family": "serif", "serif": ["Palatino"]}) rc("text", usetex = True)
This not only guarantees that images are generated using a font of our choice, but it gives a Type 1/TrueType font too. Ace!
Happy plotting.