ShellfishGene
ShellfishGene

Reputation: 345

Size of font in ggplot plot changes in relation to plot using knitr

I'm using knitr for the first time, and have a problem concering the font size in ggplot plots. This is an example plot:

d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)

In knitr I have the same plot in a chunk in my R markdown:

---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE}
library(ggplot2)
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
```

The plot looks fine in RStudio or when saved with ggsave(). However the numbers in the plot in the resulting knitr html have a much larger font size, in total and relative to the plot size:

ggsave image knitr image from html

In this example it does not matter much, but in my data the numbers start to overlap each other / run out of their cells.

An added complication is that the plot is done by a package, so I can't easily change the size option in the stat_sum call.

Upvotes: 3

Views: 3656

Answers (1)

Sam Dickson
Sam Dickson

Reputation: 5239

Try adjusting fig.height and fig.width:

---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE,fig.height=10,fig.width=10}
library(ggplot2)
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
```

If you want don't want the figure to be as large, you can adjust out.height and out.width:

---
title: "Untitled"
output: html_document
---
```{r, echo=FALSE,fig.height=10,fig.width=10,out.height=600,out.width=600}
library(ggplot2)
d <- ggplot(diamonds, aes(x = cut, y = clarity))
d + stat_sum(aes(label=..n..),geom="text",size=8)
```

Upvotes: 4

Related Questions