简体   繁体   中英

Change ggplot2 font in R Markdown: fails when knitting to PDF (but not when knitting to HTML)

I have an R Markdown file which I am compiling to PDF via knitr, Pandoc, and LaTeX. It contains several figures created using ggplot2. I want to change the font used in the figures to match the font used for the body text.

The following code works fine when knitting to HTML, ie the figure appears with Times New Roman on the axes. However, when knitting to PDF, it throws an error.

---
title: "Font test"
author: "Westcroft to Apse"
date: '2022-05-24'
output:
  pdf_document: default
  html_document:
    df_print: paged
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

library(dplyr)
library(ggplot2)

theme_set(theme_bw(base_family = "Times New Roman"))
```

```{r}
mtcars %>%
  ggplot(aes(x = wt, y = mpg)) +
  geom_point()
```

This is the error message which appears in the Render tab when I attempt to knit to PDF:

Line 21 Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x, x$y,  : 
  invalid font type
Calls: <Anonymous> ... drawDetails -> drawDetails.text -> grid.Call.graphics
In addition: There were 50 or more warnings (use warnings() to see the first 50)
Execution halted

How can I fix this?

EDIT: To be clear, this is not a question about using Times New Roman. That is not, in fact, the font I want to use. I just used it here as an example of how the same code will render to HTML but not to PDF.

Are you using Windows? If so, the problem is that R doesn't recognize the font "Times New Roman" with your reference. Change the name to "serif" to set Times New Roman as the font for the plot.

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

library(dplyr)
library(ggplot2)

theme_set(theme_bw(base_family = "serif"))
```

```{r}
mtcars %>%
ggplot(aes(x = wt, y = mpg)) +
geom_point()
```

According to this post the font "Times New Roman" is accessible as "serif". You can check this with the command windowsFonts() :

$serif
[1] "TT Times New Roman"

$sans
[1] "TT Arial"

$mono
[1] "TT Courier New"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM