Specify height and width of ggplot graph in Rmarkdown knitr output
Asked Answered
A

4

49

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?

Abduce answered 22/9, 2016 at 8:57 Comment(0)
A
114

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()
```
Abduce answered 22/9, 2016 at 8:57 Comment(4)
Would you like to elaborate on your answer for people who don't know what code chunk means?Contaminate
A code chunk is a part of the R markdown/ R Notebook formatting. This defines the space where you can write and execute your code. It is defined as ```{r} your code here ``` . More info can be found:rmarkdown.rstudio.com/lesson-3.htmlSapro
What if you want different sizes within a code chunk?Viscoid
@jzadra, I'm not sure how to do that, or if it's even possible, but creating a separate chunk for each ggplot is trivial. Just close one chunk after your first plot (with triple backticks), then open another one with the new plot specifications (triple backticks followed by a description like that in curly braces above.Didymium
G
14

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)
Garrotte answered 8/3, 2021 at 14:10 Comment(1)
When I try this the plot sizes change only in the knitted document, but not in the output of the rmd editor. It changes only if I put {r, fig.width=10,fig.height=11} in every individual chunk. Is there a global way to set the size in the output of the editor?Vituperate
T
10

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"))
Think answered 19/7, 2021 at 14:15 Comment(0)
R
0

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()
```
Rizzo answered 30/5 at 16:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.