Changing the font of R base graphic plots.

August 24, 2015
By

(This article was first published on Rcrastinate, and kindly contributed to R-bloggers)

Want to change the font used in your R plots? I got a quite simple solution that works on Mac OS.

You need the function ‘quartzFonts’. With this function, you can define additional font families to use in your R base graphic plots. The default font families are ‘sans’, ‘serif’ and ‘mono’.

Let’s say, I want to define a new font family with the ‘Avenir’ font. All I have to do is:

quartzFonts(avenir = c(“Avenir Book”, “Avenir Black”, “Avenir Book Oblique”, 
        “Avenir Black Oblique”))

The first element of the vector is the normal face, then bold face, then italic face, then bold-italic font face. The bold face is used for the title of the plots, for example.
        
Now, R knows how to interpret the font family ‘avenir’. Let’s try this:

par(family = ‘sans’) # the default of R
plot(rnorm(100), rnorm(100), main = “A plot.”)

# Now, do the same with the new ‘Avenir’ font family
par(family = ‘avenir’) # the call to ‘quartzFonts’ above has to be executed first
plot(rnorm(100), rnorm(100), main = “Another plot.”)



You might wonder where you can get the font names from. Well, simply open your Mac OS “Font Book” (it’s called “Schriftsammlung” in German) and look at the title of the font that is written in grey over the sample of the font.



I defined a function ‘.define.fonts’ in my .Rprofile file. So, each time R starts up, I have an invisible function ‘.define.fonts’ available in the environment. If I want to use one of the two alternative fonts, I can just call ‘.define.fonts()’. Here’s the function:

.define.fonts <- function () {
    quartzFonts(avenir = c(“Avenir Book”, “Avenir Black”, “Avenir Book Oblique”, 
        “Avenir Black Oblique”), helvetica = c(“Helvetica Neue Light”, 
        “Helvetica Neue Bold”, “Helvetica Neue Light Italic”, 
        “Helvetica Neue Bold Italic”))
}

You might need to change the names of the ‘helvetica’ family if you run a non-German Mac OS.

To leave a comment for the author, please follow the link and comment on their blog: Rcrastinate.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)