user6571411
user6571411

Reputation: 2969

Specify height and width of ggplot graph in Rmarkdown knitr output

I have created a plot with ggplot2 where the x-axis labels are not readable unless the plot is larger than default. When viewing in Rstudio I am able to resize dynamically. When saving with ggsave() I am able to specify height and width. How would I do this within the Rmarkdown file so that the output contains a plot of the desired size?

Upvotes: 52

Views: 104015

Answers (4)

Jakub Jędrusiak
Jakub Jędrusiak

Reputation: 469

Currently in Quarto you can add the parameters as tags to a code block:

```{r}
#| fig-width: 10
#| fig-height: 5

ggplot(df, aes(x = x, y = y)) + geom_point()
```

Upvotes: 2

Dan Chaltiel
Dan Chaltiel

Reputation: 8484

As a side-answer, note that you can also use metric-system units using ggplot2::unit():

library(ggplot2)
knitr::opts_chunk$set(fig.width=unit(18,"cm"), fig.height=unit(11,"cm"))

Upvotes: 11

Patrick
Patrick

Reputation: 1379

If you would like to do this for all plots then you can use the r setup Rmd chunk at the beginning of the file.

knitr::opts_chunk$set(echo = TRUE, fig.width = 10, fig.height = 5)

Upvotes: 16

user6571411
user6571411

Reputation: 2969

You can specify height and width in the code chunks

```{r, fig.width=10,fig.height=11}
df %>% ggplot(aes(x = x, y = y)) + geom_point()
```

Upvotes: 116

Related Questions