Search code examples
rggplot2r-markdowntypography

How to add a curly close quote or apostrophe to plot text when knitting to pdf?


I am currently plotting some data from a survey question to be used in a book. It would be useful to put typographically-correct curly quotes or what are sometimes called "smart" quotes around the survey question on the x-axis.

When creating a plot in R markdown, however, it is easy to create a typographically-correct open curly quote or apostrophe with back-tics (e.g., using one or two back-tics will create a curly ‘ or “ vs straight ' or ") but it is not obvious how to add a curly close apostrophe or quote (e.g., ’ or ”). I assume the solution is simple but was unable to figure it out via options like plotmath and hardcoding curly quotes with something like labs(x = '“some text”') didn't work. Other options like sQuote() or dQuote() work interactively but, when knitting to pdf, the curly quotes get converted to straight quotes.

How can I add a curly close quote or apostrophe to plot text when knitting in R markdown to pdf?

---
title: "Curly Quote in Plot Example"
output: pdf_document
date: "2022-08-17"
---

```{r}

library(ggplot2)

ggplot(mtcars) +
  aes(x = hp, y = mpg) +
  geom_point() +
  labs(x = "`Is MPG related to HP?`")

```

Plot of MPG vs HP with x-axis that includes a correct open curly quote and an incorrect close curly quote


Solution

  • One way we can add curly quotes on the x-axis title is by using HTML code and then render it using element_markdown from {ggtext} package.

    ---
    title: "Curly Quote in Plot Example"
    output:
      pdf_document:
        dev: cairo_pdf
    date: "2022-08-17"
    ---
    
    ```{r}
    
    library(ggplot2)
    library(ggtext)
    
    ggplot(mtcars) +
      aes(x = hp, y = mpg) +
      geom_point() +
      labs(x = "‘Is MPG related to HP?’")+
      theme(
        axis.title.x = element_markdown()
      )
    
    ```
    

    The x-axis title looks like this now,

    x-axis title with quote