How can I make an R plot use the Latin Modern font family when saved as a PDF?

做~自己de王妃 提交于 2021-02-16 15:14:51

问题


If I type

par(family='CM Roman')

then I can get a plot to display with the Computer Modern font. However, when I try to save it as a PDF, it comes up as a blank document, unlike if I take out that line.

How can I get it to save correctly as a PDF?

Also, how can I use Latin Modern instead of Computer Modern?


回答1:


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 = "lmroman*")


# 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:

Exported pdf:



来源:https://stackoverflow.com/questions/24458870/how-can-i-make-an-r-plot-use-the-latin-modern-font-family-when-saved-as-a-pdf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!