TiKz and GGplot2

tips
tidyverse
R
LaTeX
TikZ
Author

Paolo Bosetti

Published

2024-Oct-11

Better plots for PDF output

RMarkdown and Quarto notebooks can create beautiful documents via knitr and LaTeX, we know that. But we can do even better: we can use TikZ to create plots that are consistent with the document’s style (fonts), and that are vectorial, so that they can be scaled without loss of quality and in general take less memory.

The trick is to install the tikzDevice package in R, then set the dev option in the chunk options to tikz. But there’s more to it: in fact, if you set the output device to tikz, the result would be not optimal when the output format is HTML (like for the page that you are reading): the browser would probably revert to visualize the PDF plots in embedded viewers, and the result would be a bit ugly.

The solution is to instruct knitr to use the tikz device only when the output format is LaTeX. This can be done by setting the dev option in the chunk options to tikz only when the output format is LaTeX. This can be done by using the knitr::is_latex_output() function in the chunk options:

knitr::opts_chunk$set(
  fig.align = "center",
  # This for default device
  out.width = "12cm",
  # This two for high quality charts:
  fig.asp = 9/16
)
if (knitr::is_latex_output()) {
  knitr::opts_chunk$set(
    dev = "tikz"
  )
}

Now let’s make a simple GGplot2 plot and see the result in HTML and PDF. Hereafter there’s the usual PNG output:

library(tidyverse)
tibble(
  x=1:100,
  y=rchisq(length(x), df=5),
  v=sample(1:3, length(x), replace=T) %>% as.factor()
) %>% 
  ggplot(aes(x=x, y=y, shape=v)) + 
  geom_point(color="darkblue", size=2)

But look here on the right and open the PDF version of this page: the plot is now a TiKz plot, and it’s vectorial and consistent with the document’s style.

That’s all, folks!