[Tex/LaTex] Using LaTeX font in R (Computer Modern)

computer-modernfontsr

I am looking for at way to plot graphs in R, using LaTeX fonts.

In the documentation for pdfFonts in R, it states that:

There are also mappings for "ComputerModern", "ComputerModernItalic" and, as from R 3.1.0, "ArialMT" (Monotype Arial).

When using pdf(file = outputFile, width=11.692, height=8.267, family = "ComputerModern") I get the following error message:

Error in pdf(file = outputFile, width = 11.692, height = 8.267, family = "ComputerModern",  : 
  unknown family 'ComputerModern'
Execution halted

I am using R version 3.2.2 (2015-08-14). How can I use LaTeX fonts in R? Preferable without installing extra libraries.

Best Answer

This is how I did it in Windows:

  1. Install the extrafont package.
  2. Install Latin Modern fonts, e.g. from http://www.fontsquirrel.com/fonts/latin-modern-roman. Watch out, you need to install the TTF version of the font, font_import() can't handle OTF.
  3. Import the fonts using font_import().
  4. Load the fonts using loadfonts(device = "win"). Use the device = "Win" parameter to make the preview in R Studio work.
  5. Set the font family graphics parameter using par(family = "LM Roman 10").
  6. Plotting in R Studio now works and so does pdf export (see the pictures below).

This is the full code you need to use:

    # Run once
    install.packages("extrafont")
    library(extrafont)
    # Install **TTF** Latin Modern Roman fonts from www.fontsquirrel.com/fonts/latin-modern-roman
    # Import the newly installed LModern fonts, change the pattern according to the 
    # filename of the lmodern ttf files in your fonts folder
    font_import(pattern = "lmodern*")


    # Run each time
    library(extrafont)
    loadfonts(device = "win")
    par(family = "LM Roman 10")
    x <- seq(1, 10, 1)
    y <- seq(1, 10, 1)
    plot(y ~ x, main="This plot uses LaTeX font!", ylab = expression(alpha))

R Studio preview:
R Studio preview

Exported pdf:
PDF export

Related Question