R Markdown: Change plot font size when knit to HTML?

Viewed 897

I'm using R Markdown to create an HTML document with various plots in ggplot2. However, the font size shrinks considerably whenever I knit to HTML compared to when I knit to a GitHub document.

I've tried knitr::opts_chunk$set(dev.args = list(pointsize = BIG_NUMBER) but that didn't work. Any ideas? Looking for a solution that I can apply to all plots automatically, preferably with knitr. Please help!

Here's what it looks like when I knit to HTML: enter image description here Here when I copy from my R chunk output (what I want it to look like): enter image description here

1 Answers

The font size is actually the same – the apparent change in font size results from different dimensions of the plot device used: the default device (where plots are displayed in RStudio when you run code in the console) is a different one than what is used by knitr. You may compensate for this by adjusting plot dimensions using chunk options.

  • out.width and out.height set dimensions of the plot in the output.
  • fig.width and fig.height set dimensions of the graphic device.

Example:

```{r, out.height=400, out.width=800, fig.width=6, fig.height=3}
ggplot(mtcars, aes(x = mpg, y = hp)) +
    geom_point()
```

enter image description here

```{r, out.height=400, out.width=800, fig.width=4.5, fig.height=2.25}
ggplot(mtcars, aes(x = mpg, y = hp)) +
    geom_point()
```

enter image description here

You may also apply options globally by including the below chunk.

```{r, include=F}
knitr::opts_chunk$set(out.height=400, out.width=800, fig.width=6, fig.height=3)
```
Related